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:
C++
// Include all standard libraries
#include <bits/stdc++.h>
using namespace std;
// Define a function to find the kth non-repeating character
// in a string
char kthNonRepeatingChar(string str, int k)
{
// Initialize count and result variables to 0 and null
// character, respectively
int count = 0;
char result = '\0';
// Loop through each character in the string
for (int i = 0; i < str.length(); i++) {
// Assume that the current character does not repeat
bool repeating = false;
// Loop through the rest of the string to check if
// the current character repeats
for (int j = 0; j < i; j++) {
if(str[j]==str[i])
{
repeating = true;
}
}
for (int j = i + 1; j < str.length(); j++) {
if (str[i] == str[j]) {
// If the current character repeats, set the
// repeating flag to true and exit the loop
repeating = true;
}
}
// If the current character does not repeat,
// increment the count of non-repeating characters
if (!repeating) {
count++;
// If the count of non-repeating characters
// equals k, set the result variable to the
// current character and exit the loop
if (count == k) {
result = str[i];
break;
}
}
}
// Return the result variable
return result;
}
// Define the main function to test the kthNonRepeatingChar
// function
int main()
{
// Define an example string and value of k
string str = "geeksforgeeks";
int k = 3;
// Call the kthNonRepeatingChar function with the
// example string and value of k
char result = kthNonRepeatingChar(str, k);
// Check if the result variable contains a non-null
// character and print the appropriate message
if (result == '\0') {
cout << "There is no kth non-repeating character "
"in the string.\n";
}
else {
cout << "The " << k
<< "th non-repeating character in the string "
"is "
<< result << ".\n";
}
// End the program
return 0;
}
Java
// Import required libraries
import java.util.*;
// Define a class to find the kth non-repeating character
// in a string
public class Main {
public static char kthNonRepeatingChar(String str,
int k)
{
// Initialize count and result variables to 0 and
// null character, respectively
int count = 0;
char result = '\0';
// Loop through each character in the string
for (int i = 0; i < str.length(); i++) {
// Assume that the current character does not
// repeat
boolean repeating = false;
// Loop through the rest of the string to check
// if the current character repeats
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
// If the current character repeats, set
// the repeating flag to true and exit
// the loop
repeating = true;
break;
}
}
// If the current character does not repeat,
// increment the count of non-repeating
// characters
if (!repeating) {
count++;
// If the count of non-repeating characters
// equals k, set the result variable to the
// current character and exit the loop
if (count == k) {
result = str.charAt(i);
break;
}
}
}
// Return the result variable
return result;
}
// Define the main function to test the
// kthNonRepeatingChar function
public static void main(String[] args)
{
// Define an example string and value of k
String str = "geeksforgeeks";
int k = 3;
// Call the kthNonRepeatingChar function with the
// example string and value of k
char result = kthNonRepeatingChar(str, k);
// Check if the result variable contains a non-null
// character and print the appropriate message
if (result == '\0') {
System.out.println(
"There is no kth non-repeating character "
+ "in the string.");
}
else {
System.out.println(
"The " + k
+ "th non-repeating character in the string "
+ "is " + result + ".");
}
}
}
Python
# Define a function to find the kth non-repeating character
# in a string
def kthNonRepeatingChar(s: str, k: int) -> str:
# Initialize count and result variables to 0 and null
# character, respectively
count = 0
result = '\0'
# Loop through each character in the string
for i in range(len(s)):
# Assume that the current character does not repeat
repeating = False
# Loop through the rest of the string to check if
# the current character repeats
for j in range(i + 1, len(s)):
if s[i] == s[j]:
# If the current character repeats, set the
# repeating flag to true and exit the loop
repeating = True
break
# If the current character does not repeat,
# increment the count of non-repeating characters
if not repeating:
count += 1
# If the count of non-repeating characters
# equals k, set the result variable to the
# current character and exit the loop
if count == k:
result = s[i]
break
# Return the result variable
return result
# Define the main function to test the kthNonRepeatingChar
# function
if __name__ == '__main__':
# Define an example string and value of k
s = "geeksforgeeks"
k = 3
# Call the kthNonRepeatingChar function with the
# example string and value of k
result = kthNonRepeatingChar(s, k)
# Check if the result variable contains a non-null
# character and print the appropriate message
if result == '\0':
print("There is no kth non-repeating character "
"in the string.")
else:
print(f"The {k}th non-repeating character in the string "
f"is {result}.")
# This code is contributed by Susobhan Akhuli
C#
using System;
public class Program {
// Define a function to find the kth non-repeating
// character in a string
static char kthNonRepeatingChar(string str, int k)
{
// Initialize count and result variables to 0 and
// null character, respectively
int count = 0;
char result = '\0';
// Loop through each character in the string
for (int i = 0; i < str.Length; i++) {
// Assume that the current character does not
// repeat
bool repeating = false;
// Loop through the rest of the string to check
// if the current character repeats
for (int j = i + 1; j < str.Length; j++) {
if (str[i] == str[j]) {
// If the current character repeats, set
// the repeating flag to true and exit
// the loop
repeating = true;
break;
}
}
// If the current character does not repeat,
// increment the count of non-repeating
// characters
if (!repeating) {
count++;
// If the count of non-repeating characters
// equals k, set the result variable to the
// current character and exit the loop
if (count == k) {
result = str[i];
break;
}
}
}
// Return the result variable
return result;
}
// Define the main function to test the
// kthNonRepeatingChar function
static void Main(string[] args)
{
// Define an example string and value of k
string str = "geeksforgeeks";
int k = 3;
// Call the kthNonRepeatingChar function with the
// example string and value of k
char result = kthNonRepeatingChar(str, k);
// Check if the result variable contains a non-null
// character and print the appropriate message
if (result == '\0') {
Console.WriteLine(
"There is no kth non-repeating character "
+ "in the string.");
}
else {
Console.WriteLine(
"The " + k
+ "th non-repeating character in the string is "
+ result + ".");
}
}
}
// This code is contributed by Susobhan Akhuli
JavaScript
// Define a function to find the kth non-repeating character
// in a string
function kthNonRepeatingChar(str, k) {
// Initialize count and result variables to 0 and null
// character, respectively
let count = 0;
let result = "\0";
// Loop through each character in the string
for (let i = 0; i < str.length; i++) {
// Assume that the current character does not repeat
let repeating = false;
// Loop through the rest of the string to check if
// the current character repeats
for (let j = i + 1; j < str.length; j++) {
if (str[i] == str[j]) {
// If the current character repeats, set the
// repeating flag to true and exit the loop
repeating = true;
break;
}
}
// If the current character does not repeat,
// increment the count of non-repeating characters
if (!repeating) {
count++;
// If the count of non-repeating characters
// equals k, set the result variable to the
// current character and exit the loop
if (count == k) {
result = str[i];
break;
}
}
}
// Return the result variable
return result;
}
// Define the main function to test the kthNonRepeatingChar
// function
// Define an example string and value of k
let str = "geeksforgeeks";
let k = 3;
// Call the kthNonRepeatingChar function with the
// example string and value of k
let result = kthNonRepeatingChar(str, k);
// Check if the result variable contains a non-null
// character and print the appropriate message
if (result == "\0") {
console.log("There is no kth non-repeating character in the string.");
} else {
console.log(`The ${k}th non-repeating character in the string is ${result}`);
}
OutputThe 3th non-repeating character in the string is r.
Time Complexity: O(n²)
Auxiliary Space: 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:
C++
#include <bits/stdc++.h>
using namespace std;
char kthNonRepeatingChar(string str, int k)
{
// Create an empty hash map to store the counts of each
// character in the string
unordered_map<char, int> charCounts;
// Loop through the string and store the counts of each
// character in the hash map
for (int i = 0; i < str.length(); i++) {
charCounts[str[i]]++;
}
// Loop through the string and find the kth
// non-repeating character
int nonRepeatingCount = 0;
for (int i = 0; i < str.length(); i++) {
if (charCounts[str[i]] == 1) {
nonRepeatingCount++;
if (nonRepeatingCount == k) {
// When the count of non-repeating
// characters equals k, return the character
return str[i];
}
}
}
// If there is no kth non-repeating character in the
// string, return the null character
return '\0';
}
int main()
{
string str = "geeksforgeeks";
int k = 3;
char result = kthNonRepeatingChar(str, k);
if (result == '\0') {
cout << "There is no kth non-repeating character "
"in the string.\n";
}
else {
cout << "The " << k
<< "th non-repeating character in the string "
"is "
<< result << ".\n";
}
return 0;
}
Java
import java.util.*;
public class Main {
public static char kthNonRepeatingChar(String str, int k) {
// Create an empty hash map to store the counts of each
// character in the string
Map<Character, Integer> charCounts = new HashMap<>();
// Loop through the string and store the counts of each
// character in the hash map
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
charCounts.put(c, charCounts.getOrDefault(c, 0) + 1);
}
// Loop through the string and find the kth
// non-repeating character
int nonRepeatingCount = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (charCounts.get(c) == 1) {
nonRepeatingCount++;
if (nonRepeatingCount == k) {
// When the count of non-repeating
// characters equals k, return the character
return c;
}
}
}
// If there is no kth non-repeating character in the
// string, return the null character
return '\0';
}
public static void main(String[] args) {
String str = "geeksforgeeks";
int k = 3;
char result = kthNonRepeatingChar(str, k);
if (result == '\0') {
System.out.println("There is no kth non-repeating character " +
"in the string.");
} else {
System.out.println("The " + k + "th non-repeating character " +
"in the string is " + result + ".");
}
}
}
Python
# Python code of the above approach
def kth_non_repeating_char(string, k):
# Create an empty dictionary to store
# the counts of each character in the string
char_counts = {}
# Loop through the string and store
# the counts of each character in the dictionary
for char in string:
if char in char_counts:
char_counts[char] += 1
else:
char_counts[char] = 1
# Loop through the string and find the kth non-repeating character
non_repeating_count = 0
for char in string:
if char_counts[char] == 1:
non_repeating_count += 1
if non_repeating_count == k:
# When the count of non-repeating
# characters equals k, return the character
return char
# If there is no kth non-repeating character in the string, return None
return None
# Main function
if __name__ == "__main__":
string = "geeksforgeeks"
k = 3
result = kth_non_repeating_char(string, k)
if result is None:
print("There is no kth non-repeating character in the string.")
else:
print(f"The {k}th non-repeating character in the string is {result}.")
# This code is contributed by Susobhan Akhuli
C#
using System;
using System.Collections.Generic;
class Gfg
{
static char kthNonRepeatingChar(string str, int k)
{
// Create a dictionary to store the counts of each character in the string
Dictionary<char, int> charCounts = new Dictionary<char, int>();
// Loop through the string and store
// the counts of each character in the dictionary
foreach (char c in str)
{
if (charCounts.ContainsKey(c))
{
charCounts[c]++;
}
else
{
charCounts[c] = 1;
}
}
// Loop through the string and find
// the kth non-repeating character
int nonRepeatingCount = 0;
foreach (char c in str)
{
if (charCounts[c] == 1)
{
nonRepeatingCount++;
if (nonRepeatingCount == k)
{
// When the count of non-repeating characters equals k, return the character
return c;
}
}
}
// If there is no kth non-repeating character in the string, return the null character
return '\0';
}
static void Main()
{
string str = "geeksforgeeks";
int k = 3;
char result = kthNonRepeatingChar(str, k);
if (result == '\0')
{
Console.WriteLine("There is no kth non-repeating character in the string.");
}
else
{
Console.WriteLine($"The {k}th non-repeating character in the string is {result}.");
}
}
}
JavaScript
function kthNonRepeatingChar(str, k) {
// Create an empty map to store the counts of each
// character in the string
const charCounts = new Map();
// Loop through the string and store the counts of each
// character in the map
for (let i = 0; i < str.length; i++) {
const char = str[i];
charCounts.set(char, (charCounts.get(char) || 0) + 1);
}
// Loop through the string and find the kth non-repeating character
let nonRepeatingCount = 0;
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (charCounts.get(char) === 1) {
nonRepeatingCount++;
if (nonRepeatingCount === k) {
// When the count of non-repeating characters equals k,
// return the character
return char;
}
}
}
// If there is no kth non-repeating character in the string,
// return the null character
return '\0';
}
// Main function
function main() {
const str = "geeksforgeeks";
const k = 3;
const result = kthNonRepeatingChar(str, k);
if (result === '\0') {
console.log("There is no kth non-repeating character in the string.");
} else {
console.log(`The ${k}th non-repeating character in the string is ${result}.`);
}
}
main();
OutputThe 3th non-repeating character in the string is r.
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem