imashutosh51

Find the Duplicate Number

Oct 18th, 2022 (edited)
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. '''
  2. Logic:
  3. 0 1 2 3 4
  4. 3 1 3' 4 2
  5. IF we are using the index of the elements also, it becomes the Cyclic linked list.
  6. 3->4->2->3'->4(here we have reached to somewhere where we already visited)
  7. so it's something like circular linked list so we can use slow and fast pointer
  8. to find the element.
  9.  
  10. ### Here if the array size is n+1 then the array values will be only bw [1,n] inclusive so all the elements of the array can be used as the index.
  11. '''
  12. class Solution:
  13.     def findDuplicate(self, arr: List[int]) -> int:
  14.         slow=arr[0]
  15.         fast=arr[0]
  16.         while True: #here we are checking inside just because one reason that slow and fast both points same place in first iteration
  17.             slow=arr[slow]
  18.             fast=arr[arr[fast]]
  19.             if slow==fast:
  20.                 break
  21.         slow=arr[0]
  22.         while slow!=fast:
  23.             slow = arr[slow]
  24.             fast = arr[fast]
  25.         return slow
  26.        
  27.        
Advertisement
Add Comment
Please, Sign In to add comment