Skip to content

Commit 975be50

Browse files
authored
Create K’th Non-repeating Character in Python using List Comprehension and OrderedDict
1 parent f3bf945 commit 975be50

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def kthRepeating(input,k):
2+
3+
# OrderedDict returns a dictionary data
4+
# structure having characters of input
5+
# string as keys in the same order they
6+
# were inserted and 0 as their default value
7+
dict=OrderedDict.fromkeys(input,0)
8+
9+
# now traverse input string to calculate
10+
# frequency of each character
11+
for ch in input:
12+
dict[ch]+=1
13+
14+
# now extract list of all keys whose value
15+
# is 1 from dict Ordered Dictionary
16+
nonRepeatDict = [key for (key,value) in dict.items() if value==1]
17+
18+
# now return (k-1)th character from above list
19+
if len(nonRepeatDict) < k:
20+
return 'Less than k non-repeating characters in input.'
21+
else:
22+
return nonRepeatDict[k-1]
23+
24+
# Driver function
25+
if __name__ == "__main__":
26+
input = "Ankur Ranjan"
27+
k = 3
28+
print (kthRepeating(input, k))

0 commit comments

Comments
 (0)