VOOZH about

URL: https://www.geeksforgeeks.org/dsa/kth-non-repeating-character/

⇱ K'th Non-repeating Character - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

K'th Non-repeating Character

Last Updated : 15 Jul, 2024

Given a string str of length n (1 <= n <= 106) and a number k, the task is to find the kth non-repeating character in the string.

Examples:

Input : str = geeksforgeeks, k = 3
Output : r
Explanation: 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 is mainly an extension of the First non-repeating character problem.

K'th Non-repeating Character using Nested Loop:

A Simple Solution is to run two loops. Start traversing from the left side. For every character, check if it repeats or not. If the character doesn't repeat, increment the count of non-repeating characters. When the count becomes k, return the character.

Below is the implementation of the above idea:


Output
The 3th non-repeating character in the string is r.

Time Complexity: O(n²)
AuxiliarySpace: O(1)

K'th Non-repeating Character using Hashing:

  • Create an empty hash map to store character counts.
  • Loop through the string and update the counts of each character in the hash map.
  • Loop through the string again and find the kth non-repeating character by checking the count of each character in the hash map.

Below is the implementation of the above idea:


Output
The 3th non-repeating character in the string is r.

Time Complexity: O(n)
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: