About Me

My photo
Experienced Web Developer using C#, ASP Classic (VBScript) and ASP.NET, MySQL, T-SQL, and other SQL variants, JavaScript (W3Schools Certified and very well versed in jQuery and learning Dojo), and XML. Heavy interest in JavaScript, framework creation on various language platforms, and keeping up with the best industry-accepted practices.

Wednesday, August 3, 2011

Unique value in an array?

So, someone recently told me about an interview question they heard about for some job at Amazon. I thought the question and answer were neat, so I figured I'd share it.

The question goes: "If you were given an array filled with a bunch of numbers, where every number was duplicated exactly one time except for one number, which is only in the array once, what is the most efficient way to find the unique value?"

The answer is to iterate through the array one time, performing XOR on each of the numbers. At the end, the value you have will be the unique value.

Want to see it for yourself?

Here's a JavaScript snippet I wrote to prove it on a smaller scale. This will work on arrays of any size, however.



Speaking of XOR and interview questions, I was a part of creating the team test we give people who want to join our team, and one of the questions was to have the person write a piece of code that would swap variable values without using a 3rd variable as a "value bucket". I decided to try to do this in one line using XOR, and I pulled it off.

The JS for it is:

2 comments: