Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Logic:
- 0 1 2 3 4
- 3 1 3' 4 2
- IF we are using the index of the elements also, it becomes the Cyclic linked list.
- 3->4->2->3'->4(here we have reached to somewhere where we already visited)
- so it's something like circular linked list so we can use slow and fast pointer
- to find the element.
- ### 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.
- '''
- class Solution:
- def findDuplicate(self, arr: List[int]) -> int:
- slow=arr[0]
- fast=arr[0]
- while True: #here we are checking inside just because one reason that slow and fast both points same place in first iteration
- slow=arr[slow]
- fast=arr[arr[fast]]
- if slow==fast:
- break
- slow=arr[0]
- while slow!=fast:
- slow = arr[slow]
- fast = arr[fast]
- return slow
Advertisement
Add Comment
Please, Sign In to add comment