Popular Posts

Sunday, July 17, 2011

Finding repetitions in an array (constant space)

Problem:
              You have a read-only array A[1..n] which is populated by numbers from 1..n-1, which implies atleast one repetition. However, there can be more. Find any one repeated number in linear time using constant space.          
    
Solution:
             Consider this problem as Finding a loop in a linked list.
             Since array contents are A[1..n-1] that means 'n' will not be there so we can make our starting point as 'n' which is last element in the array.
             Once we found whether loop exists or not then we can move one pointer from the beginning and one from where we found the loops exists.
             Now we can find the repeating element once the two pointer points to same value(Repeating element)


Complexity:
                  
Code:

No comments:

Post a Comment