-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathfind-duplicate-element.py
52 lines (42 loc) · 1.38 KB
/
find-duplicate-element.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
#164
Google
You are given an array of length n + 1 whose elements belong to the set {1, 2, ..., n}.
By the pigeonhole principle, there must be a duplicate. Find it in linear time and space.
"""
import random
def generateList():
n = random.randint(10,100)
l = [x for x in range(1,n)]
l.append(random.choice(l))
random.shuffle(l)
return l
def summationTillN(n):
return int(n*(n+1)/2)
def findDuplicate(l):
actualSum = sum(l)
expectedSum = summationTillN(len(l)-1)
return actualSum - expectedSum
def findDuplicateUsingCount(l):
return [x for x in l if l.count(x)==2][0]
def main():
testCaseCount = 10
testCasesPassed = 0
testCasesFailed = 0
for _ in range(testCaseCount):
listWithDuplicate = generateList()
duplicateValue = findDuplicate(listWithDuplicate)
duplicateValueUsingCount = findDuplicateUsingCount(listWithDuplicate)
try:
assert duplicateValue == duplicateValueUsingCount
print(listWithDuplicate, duplicateValue)
testCasesPassed += 1
except:
print("Error:", listWithDuplicate, duplicateValue, duplicateValueUsingCount)
testCasesFailed += 1
print()
print("Total test cases:", testCaseCount)
print("Test cases passed:", testCasesPassed)
print("Test cases failed:", testCasesFailed)
if __name__ == "__main__":
main()