VOOZH about

URL: https://www.geeksforgeeks.org/python/kth-non-repeating-character-python-using-list-comprehension-ordereddict/

⇱ K’th Non-repeating Character in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

K’th Non-repeating Character in Python

Last Updated : 14 Nov, 2025

Given a string 's' and an integer 'k', the task is to find the K’th non-repeating character in the string. A non-repeating character is one that appears exactly once.

Example:

Input: "geeksforgeeks"
k=3

Output: "r"

Explanation: In "geeksforgeeks", the characters that appear only once are f, o, and r. The third non-repeating character is "r".

Using collections.Counter

Counter quickly counts how many times each character appears, making it easy to pick out non-repeating ones.


Output
r

Explanation:

  • Counter(s): creates a dictionary of individual characters as keys and their frequencies as values ({'e': 4, 'g': 2, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}).
  • [ch for ch in s if c[ch] == 1]: collects characters that appear only once 'c'.
  • res[k - 1] if k <= len(res) else None: prints the k'th element of "res" if k is less than the length of "res", else it prints none.

Using OrderedDict

OrderedDict keeps track of the order characters appear while counting them.


Output
r

Explanation:

  • OrderedDict(): Stores characters while preserving their order of appearance.
  • freq.get(ch, 0) + 1: Counts how many times each character appears.
  • [ch for ch, cnt in freq.items() if cnt == 1]: Collects only the non-repeating characters.

Using Regular Dictionary

This method uses a normal dictionary to count characters, then collects the non-repeating ones.


Output
r

Explanation:

  • if freq[ch] == 1: Checks for characters that appear only once.
  • res.append(ch): Stores non-repeating characters in order.

Using List Comprehension

This approach counts frequencies and filters non-repeating characters using list comprehension.


Output
r

Explanation: [ch for ch in s if freq[ch] == 1]: Collects characters appearing only once.

Related Articles:

Comment