K’th Non-repeating Character in Python using List Comprehension and OrderedDict
Last Updated :
21 Jul, 2022
Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples:
Input : str = geeksforgeeks, k = 3
Output : r
First non-repeating character is f,
second is o and third is r.
Input : str = geeksforgeeks, k = 2
Output : o
Input : str = geeksforgeeks, k = 4
Output : Less than k non-repeating
characters in input.
This problem has existing solution please refer link. We can solve this problem quickly in python using List Comprehension and OrderedDict.
Implementation:
Python3
from collections import OrderedDict
def kthRepeating( input ,k):
dict = OrderedDict.fromkeys( input , 0 )
for ch in input :
dict [ch] + = 1
nonRepeatDict = [key for (key,value) in dict .items() if value = = 1 ]
if len (nonRepeatDict) < k:
return 'Less than k non-repeating characters in input.'
else :
return nonRepeatDict[k - 1 ]
if __name__ = = "__main__" :
input = "geeksforgeeks"
k = 3
print (kthRepeating( input , k))
|
Share your thoughts in the comments
Please Login to comment...