Skip to content
Related Articles

Related Articles

Improve Article

K’th Non-repeating Character in Python using List Comprehension and OrderedDict

  • Difficulty Level : Medium
  • Last Updated : 23 Nov, 2020

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?


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.

# Function to find k'th non repeating character 
# in string 
from collections import OrderedDict 
def kthRepeating(input,k): 
    # OrderedDict returns a dictionary data 
        # structure having characters of input 
    # string as keys in the same order they 
        # were inserted and 0 as their default value 
    # now traverse input string to calculate 
        # frequency of each character 
    for ch in input
    # now extract list of all keys whose value 
        # is 1 from dict Ordered Dictionary 
    nonRepeatDict = [key for (key,value) in dict.items() if value==1
    # now return (k-1)th character from above list 
    if len(nonRepeatDict) < k: 
        return 'Less than k non-repeating characters in input.' 
        return nonRepeatDict[k-1
# Driver function 
if __name__ == "__main__"
    input = "geeksforgeeks"
    k = 3
    print (kthRepeating(input, k)) 



This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up
Recommended Articles
Page :