forked from devAmoghS/Python-Interview-Problems-for-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
first_non_repeating.py
54 lines (40 loc) · 1.12 KB
/
first_non_repeating.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
# Given an input string, it gives the
# first non repeating character in it
# There are two implementations below
# 1. has less space complexity
# 2. has less time complexity
def first_non_repeating(input_string):
frequency = dict()
flag = None
for char in input_string:
if char in frequency.keys():
frequency[char] += 1
else:
frequency[char] = 0
for char in input_string:
if frequency[char] == 0:
flag = char
break
return flag
# lesser time complexity
# more space complexity
# obvious space-time trade-off
def first_non_repeating_v2(input_string):
flag = None
repeating = []
non_repeating = []
for char in input_string:
if char in non_repeating:
non_repeating.remove(char)
repeating.append(char)
else:
non_repeating.append(char)
if len(non_repeating) == 0:
pass
else:
flag = non_repeating[0]
return flag
result = first_non_repeating("djebdedbekfrnkfnduwbdwkd")
print(result) # j
result = first_non_repeating("aabbcc")
print(result) # None