Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to sum to find the repeating number?

Tags:

algorithm

Problem: you are given a sequence of numbers from 1 to n-1 with one of the numbers repeating only once. (example: 1 2 3 3 4 5). how can you find the repeating number?

Very often the so called "smart" answer to this question is to sum it up and find the difference from the expected sum. But why not just walk through the list and check the number before it? Both are O(n). Am I missing something?

like image 745
erotsppa Avatar asked Nov 28 '22 22:11

erotsppa


1 Answers

The "smart" answer is the best solution when the list is not sorted, because it visits each element only once and uses O(1) additional space. If the list is sorted, there is even a O(log n) solution: You can do a binary search. By looking at the central element, you can see if the duplicate number is before or after that element and continue bisecting until you found it.

Example:

1 2 2 3 4 5 6

The central element is 3, but it is in the fourth position, so the duplicate must be before it. Next check is the 2 in second position, so we have to look after the second position etc.

like image 76
Sven Marnach Avatar answered Dec 10 '22 08:12

Sven Marnach