Created
May 23, 2019 14:28
-
-
Save priyankvex/92094ef3ce67966c5bba80d264670fa1 to your computer and use it in GitHub Desktop.
Find the duplicate number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
https://scammingthecodinginterview.com | |
Week 5: Two Pointer | |
Problem: 2 | |
""" | |
class Solution(object): | |
def solve(self, a): | |
slow = a[0] | |
fast = a[a[0]] | |
while (slow != fast): | |
slow = a[slow] | |
fast = a[a[fast]] | |
slow = 0 | |
while slow != fast: | |
slow = a[slow] | |
fast = a[fast] | |
return slow | |
if __name__ == "__main__": | |
a = [1, 2, 3, 4, 5, 1] | |
ans = Solution().solve(a) | |
print(ans) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will break if the input array has anything but integers.
The naïve solution, with two for-loops, is more robust and simpler to read - but O(n²) time complexity: