-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathduplicates.py
58 lines (43 loc) · 1.47 KB
/
duplicates.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
53
54
55
56
57
58
import math
def firstDuplicate(xs):
"""
Finds the first duplicate element in xs
Time O(n)
Space O(1)
"""
for x in xs:
positive_x = abs(x)
positive_x_index = positive_x - 1
xs[positive_x_index] *= -1
if xs[positive_x_index] > 0:
return positive_x
return -1
def firstNotRepeatingCharacter(string):
"""
Finds the first non repeating element in xs
Time O(n)
Space O(1)
"""
alphabet_len = ord('z') - ord('a') + 1
unique_letter_index = [None] * alphabet_len
for index, character in enumerate(string):
alphabet_position = ord(character) - ord('a')
if unique_letter_index[alphabet_position] is None:
unique_letter_index[alphabet_position] = index
else:
unique_letter_index[alphabet_position] = math.inf
min_index = math.inf
result = '_'
for alphabet_position, first_occurence in enumerate(unique_letter_index):
if first_occurence is not None and min_index > first_occurence:
min_index = first_occurence
result = chr(alphabet_position + ord('a'))
if result != math.inf:
return result
else:
return '_'
# print(firstNotRepeatingCharacter('abacabad'))
# print(firstNotRepeatingCharacter('abacabaabacaba'))
# print(firstNotRepeatingCharacter('z'))
# print(firstNotRepeatingCharacter('bcccccccb'))
# print(firstNotRepeatingCharacter('abcdefghijklmnopqrstuvwxyziflskecznslkjfabe'))