<p>What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice.</p>

<p>So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm.</p>

[{'answer_id': 35192, 'author': 'Jason Bunting', 'author_id': 1790, 'author_profile': 'https://Stackoverflow.com/users/1790', 'pm_score': 0, 'selected': False, 'text': '<p>You need to specify what you mean by "best" - to some, speed is all that matters and would qualify an answer as "best" - for others, they might forgive a few hundred milliseconds if the solution was more readable.</p>\n\n<p>"Best" is subjective unless you are more specific.</p>\n\n<hr>\n\n<p>That said:</p>\n\n<p>Iterate through the numbers, for each number search the list for that number and when you reach the number that returns only a 1 for the number of search results, you are done.</p>\n'}, {'answer_id': 35195, 'author': 'csmba', 'author_id': 350, 'author_profile': 'https://Stackoverflow.com/users/350', 'pm_score': 4, 'selected': False, 'text': '<p><strong>O(N) time, O(N) memory</strong></p>\n\n<p>HT= Hash Table </p>\n\n<p>HT.clear()\ngo over the list in order \nfor each item you see</p>\n\n<pre><code>if(HT.Contains(item)) -&gt; HT.Remove(item)\nelse\nht.add(item)\n</code></pre>\n\n<p>at the end, the item in the HT is the item you are looking for.</p>\n\n<p>Note (credit @Jared Updike): This system will find all Odd instances of items.</p>\n\n<hr>\n\n<p><strong>comment</strong>: I don\'t see how can people vote up solutions that give you NLogN performance. in which universe is that "better" ? \nI am even more shocked you marked the accepted answer s NLogN solution...</p>\n\n<p>I do agree however that if memory is required to be constant, then NLogN would be (so far) the best solution.</p>\n'}, {'answer_id': 35200, 'author': 'Farinha', 'author_id': 2841, 'author_profile': 'https://Stackoverflow.com/users/2841', 'pm_score': 1, 'selected': False, 'text': '<p>I would say that using a sorting algorithm and then going through the sorted list to find the number is a good way to do it.</p>\n\n<p>And now the problem is finding "the best" sorting algorithm. There are a lot of sorting algorithms, each of them with its strong and weak points, so this is quite a complicated question. The <a href="http://en.wikipedia.org/wiki/Sorting_algorithm" rel="nofollow noreferrer">Wikipedia entry</a> seems like a nice source of info on that.</p>\n'}, {'answer_id': 35204, 'author': 'levand', 'author_id': 3044, 'author_profile': 'https://Stackoverflow.com/users/3044', 'pm_score': 0, 'selected': False, 'text': '<p>Seems like the best you could do is to iterate through the list, for every item add it to a list of "seen" items or else remove it from the "seen" if it\'s already there, and at the end your list of "seen" items will include the singular element. This is O(n) in regards to time and n in regards to space (in the worst case, it will be much better if the list is sorted). </p>\n\n<p>The fact that they\'re integers doesn\'t really factor in, since there\'s nothing special you can do with adding them up... is there?</p>\n\n<p><strong>Question</strong></p>\n\n<p>I don\'t understand why the selected answer is "best" by any standard. O(N*lgN) > O(N), and it changes the list (or else creates a copy of it, which is still more expensive in space and time). Am I missing something?</p>\n'}, {'answer_id': 35235, 'author': 'hoyhoy', 'author_id': 3499, 'author_profile': 'https://Stackoverflow.com/users/3499', 'pm_score': -1, 'selected': False, 'text': '<p>You could simply put the elements in the set into a hash until you find a collision.  In ruby, this is a one-liner.</p>\n\n<pre><code>def find_dupe(array)\n  h={}\n  array.detect { |e| h[e]||(h[e]=true; false) }\nend\n</code></pre>\n\n<p>So, <code>find_dupe([1,2,3,4,5,1])</code> would return 1. </p>\n\n<p>This is actually a common "trick" interview question though.  It is normally about a list of consecutive integers with one duplicate.  In this case the interviewer is often looking for you to use the Gaussian sum of <em>n</em>-integers trick e.g. <code>n*(n+1)/2</code> subtracted from the actual sum.  The textbook answer is something like this. </p>\n\n<pre><code>def find_dupe_for_consecutive_integers(array)\n  n=array.size-1   # subtract one from array.size because of the dupe\n  array.sum - n*(n+1)/2\nend\n</code></pre>\n'}, {'answer_id': 35244, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 0, 'selected': False, 'text': '<p>Depends on how large/small/diverse the numbers are though. A radix sort might be applicable which would reduce the sorting time of the O(N log N) solution by a large degree.</p>\n'}, {'answer_id': 35271, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 8, 'selected': True, 'text': '<p>The fastest (O(n)) and most memory efficient (O(1)) way is with the XOR operation.</p>\n\n<p>In C:</p>\n\n<pre><code>int arr[] = {3, 2, 5, 2, 1, 5, 3};\n\nint num = 0, i;\n\nfor (i=0; i &lt; 7; i++)\n    num ^= arr[i];\n\nprintf("%i\\n", num);\n</code></pre>\n\n<p>This prints "1", which is the only one that occurs once.</p>\n\n<p>This works because the first time you hit a number it marks the num variable with itself, and the second time it unmarks num with itself (more or less). The only one that remains unmarked is your non-duplicate.</p>\n'}, {'answer_id': 35348, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 4, 'selected': False, 'text': '<p>By the way, you can expand on this idea to very quickly find <em>two</em> unique numbers among a list of duplicates.</p>\n\n<p>Let\'s call the unique numbers a and b.  First take the XOR of everything, as Kyle suggested.  What we get is a^b.  We know a^b != 0, since a != b.  Choose any 1 bit of a^b, and use that as a mask -- in more detail: choose x as a power of 2 so that x &amp; (a^b) is nonzero.</p>\n\n<p>Now split the list into two sublists -- one sublist contains all numbers y with y&amp;x == 0, and the rest go in the other sublist.  By the way we chose x, we know that a and b are in different buckets.  We also know that each pair of duplicates is still in the same bucket.  So we can now apply ye olde "XOR-em-all" trick to each bucket independently, and discover what a and b are completely.</p>\n\n<p>Bam.</p>\n'}, {'answer_id': 37523, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>The sorting method and the XOR method have the same time complexity. The XOR method is only O(n) if you assume that bitwise XOR of two strings is a constant time operation. This is equivalent to saying that the size of the integers in the array is bounded by a constant. In that case you can use Radix sort to sort the array in O(n).</p>\n\n<p>If the numbers are not bounded, then bitwise XOR takes time O(k) where k is the length of the bit string, and the XOR method takes O(nk). Now again Radix sort will sort the array in time O(nk).</p>\n'}, {'answer_id': 41632, 'author': 'Ralph M. Rickenbach', 'author_id': 4549416, 'author_profile': 'https://Stackoverflow.com/users/4549416', 'pm_score': 2, 'selected': False, 'text': "<p>Kyle's solution would obviously not catch situations were the data set does not follow the rules. If all numbers were in pairs the algorithm would give a result of zero, the exact same value as if zero would be the only value with single occurance.</p>\n\n<p>If there were multiple single occurance values or triples, the result would be errouness as well.</p>\n\n<p>Testing the data set might well end up with a more costly algorithm, either in memory or time.</p>\n\n<p>Csmba's solution does show some errouness data (no or more then one single occurence value), but not other (quadrouples). Regarding his solution, depending on the implementation of HT, either memory and/or time is more then O(n).</p>\n\n<p>If we cannot be sure about the correctness of the input set, sorting and counting or using a hashtable counting occurances with the integer itself being the hash key would both be feasible.</p>\n"}, {'answer_id': 25834770, 'author': 'SuperNova', 'author_id': 3464971, 'author_profile': 'https://Stackoverflow.com/users/3464971', 'pm_score': 1, 'selected': False, 'text': '<p>Implementation in Ruby:</p>\n\n<pre><code>a = [1,2,3,4,123,1,2,.........]\nt = a.length-1\nfor i in 0..t\n   s = a.index(a[i])+1\n   b = a[s..t]\n   w = b.include?a[i]\n   if w == false\n       puts a[i]\n   end\nend\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/35185', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/380/']