Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Created May 23, 2019 14:28
Show Gist options
  • Save priyankvex/92094ef3ce67966c5bba80d264670fa1 to your computer and use it in GitHub Desktop.
Save priyankvex/92094ef3ce67966c5bba80d264670fa1 to your computer and use it in GitHub Desktop.
Find the duplicate number
"""
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)
@guiambros
Copy link

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:

a = [1, "a", 0, 3, None, 5, 6, 1, 7, 8, 9]

def find_duplicate(arr):
    for i, a in enumerate(arr):
        for j, b in enumerate(arr[i+1:]):
            if a == b:
                print(f"Duplicate found ({i}, {j+1})")

find_duplicate(a)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment