Skip to content

Commit 73fa7f1

Browse files
committed
issue #1082: Array: Find first duplicate value in Python
1 parent c15519e commit 73fa7f1

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Arrays/find_first_duplicate_value.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'''
2+
In the code I implemented a solution using Floyd's Tortoise and Hare algorithm
3+
for finding the first integer that appears more than once in an array of integers.
4+
5+
The first solution has a time complexity of O(n) and a space complexity of O(1).
6+
It uses the fact that the integers in the array are between 1 and n, inclusive, where n is the length of the array.
7+
The solution works by using the array itself as a hash table,
8+
by marking an integer as negative if it is encountered for the first time,
9+
and returning it if it is already marked negative.
10+
11+
'''
12+
13+
def find_duplicate(nums):
14+
slow = fast = nums[0]
15+
while True:
16+
slow = nums[slow]
17+
fast = nums[nums[fast]]
18+
if slow == fast:
19+
break
20+
21+
slow = nums[0]
22+
while slow != fast:
23+
slow = nums[slow]
24+
fast = nums[fast]
25+
26+
return slow

0 commit comments

Comments
 (0)