Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find repeating in O(n) and constant space [duplicate]

Tags:

algorithm

Possible Duplicate:
Easy interview question got harder: given numbers 1..100, find the missing number(s)
Find the missing and duplicate elements in an array in linear time and constant space

I saw an interesting Question on one forum.

you have 100 elements from 1 to 100 but byy mistake one of those number overlapped another by repeating itself. E.g. 1,99,3,...,99,100 Array is not in sorted format , how to find the repeating number ?

I know Hash can do it O(n) time and O(n) space, I need O(1) space.

like image 913
user973931 Avatar asked Jan 31 '12 00:01

user973931


People also ask

How do you find duplicates in array O space?

Naive approach: Use 2 loops. Check each element in the array with all other elements in the array and check if it has the same value. Sorting approach: Sort the array, this will bring all the duplicates together if present. Now navigate the array and check the adjacent elements to check for duplicates.


1 Answers

Calculate two sums: sum and square sum.

In your example:

sum = 1+99+3...+100

sq_sum = 1^2+99^2+3^2+...+100^2

Assume y replaced x in the sequence.

sum = n(n+1)/2 -y+x.
sq_sum = n(n+1)(2n+1)/6 -x^2 +y^2

Now, solve for x & y.

Constant space and O(n) time.

How to solve for x and y

From equation:

x = sum - n(n+1)/2 +y

Substitute this in the second equation:

sq_sum = n(n+1)(2n+1)/6 -(sum - n(n+1)/2 +y)^2 +y^2

Note that y^2 cancels and you are left with a linear equation with only one unknown:y. Solve it!

like image 52
ElKamina Avatar answered Sep 22 '22 04:09

ElKamina