K’th Non-repeating Character
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 is mainly an extension of the First non-repeating character problem.
Brute Force/Naive Approach:
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.
Steps to implement the approach:
- Define a function named kthNonRepeatingChar that takes in a string and an integer k as arguments and returns a character.
- Initialize a count variable to 0 and a result variable to a null character.
- Loop through the string characters from left to right using a for loop.
- For each character, loop through the string characters from the current index + 1 to the end of the string using another for loop.
- If the current character is found in the remaining string characters, set the repeating flag to true and break out of the inner loop.
- If the repeating flag is false, increment the count and check if the count is equal to k.
- If the count is equal to k, set the result variable to the current character and break out of the outer loop.
- Return the result variable.
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 = 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 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 + "." ); } } } |
Python3
# 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 |
The 3th non-repeating character in the string is r.
Time Complexity: O(n²)
Auxiliary Space: O(1)
Hashmap Approach :
- 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.
Steps to implement the approach:
- Initialize an empty hash map charCounts.
- Loop through the string str:
- If the current character is not in the hash map, insert it with a count of 1.
- If the current character is already in the hash map, increment its count.
- Loop through the string str:
- If the count of the current character in the hash map is 1, increment the non-repeating character count count.
- If the count is equal to k, return the current character.
- If no kth non-repeating character is found, return the null character ‘\0‘.
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; } |
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++; } else { charCounts = 1; } } // Loop through the string and find // the kth non-repeating character int nonRepeatingCount = 0; foreach ( char c in str) { if (charCounts == 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}." ); } } } |
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 + "." ); } } } |
The 3th non-repeating character in the string is r.
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3 (O(n) and requires one traversal)
The idea is to use two auxiliary arrays of size 256 (Assuming that characters are stored using 8 bits). The two arrays are:
count[x] : Stores count of character 'x' in str. If x is not present, then it stores 0. index[x] : Stores indexes of non-repeating characters in str. If a character 'x' is not present or x is repeating, then it stores a value that cannot be a valid index in str[]. For example, length of string.
- Initialize all values in count[] as 0 and all values in index[] as n where n is the length of the string.
- Traverse the input string str and do the following for every character c = str[i].
- Increment count[x].
- If count[x] is 1, then store index of x in index[x], i.e., index[x] = i
- If count[x] is 2, then remove x from index[], i.e., index[x] = n
- Now index[] has indexes of all non-repeating characters. Sort index[] in increasing order so that we get kth smallest element at index[k]. Note that this step takes O(1) time because there are only 256 elements in the index[].
Below is the implementation of the above idea.
C++
// C++ program to find k'th non-repeating character // in a string #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 256; // Returns index of k'th non-repeating character in // given string str[] int kthNonRepeating(string str, int k) { int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int count[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] int index[MAX_CHAR]; // Initialize counts of all characters and indexes // of non-repeating characters. for ( int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for ( int i = 0; i < n; i++) { // Find current character and increment its // count char x = str[i]; ++count[x]; // If this is first occurrence, then set value // in index as index of it. if (count[x] == 1) index[x] = i; // If character repeats, then remove it from // index[] if (count[x] == 2) index[x] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only sort(index, index+MAX_CHAR); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k-1] != n)? index[k-1] : -1; } // Driver code int main() { string str = "geeksforgeeks" ; int k = 3; int res = kthNonRepeating(str, k); (res == -1)? cout << "There are less than k non-" "repeating characters" : cout << "k'th non-repeating character" " is " << str[res]; return 0; } |
Java
// Java program to find k'th non-repeating character // in a string import java.util.Arrays; class GFG { public static int MAX_CHAR = 256 ; // Returns index of k'th non-repeating character in // given string str[] static int kthNonRepeating(String str, int k) { int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int [] count = new int [MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] int [] index = new int [MAX_CHAR]; // Initialize counts of all characters and indexes // of non-repeating characters. for ( int i = 0 ; i < MAX_CHAR; i++) { count[i] = 0 ; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for ( int i = 0 ; i < n; i++) { // Find current character and increment its // count char x = str.charAt(i); ++count[x]; // If this is first occurrence, then set value // in index as index of it. if (count[x] == 1 ) index[x] = i; // If character repeats, then remove it from // index[] if (count[x] == 2 ) index[x] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only Arrays.sort(index); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k- 1 ] != n)? index[k- 1 ] : - 1 ; } // driver program public static void main (String[] args) { String str = "geeksforgeeks" ; int k = 3 ; int res = kthNonRepeating(str, k); System.out.println(res == - 1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + str.charAt(res)); } } // Contributed by Pramod Kumar |
Python 3
# Python 3 program to find k'th # non-repeating character in a string MAX_CHAR = 256 # Returns index of k'th non-repeating # character in given string str[] def kthNonRepeating( str , k): n = len ( str ) # count[x] is going to store count of # character 'x' in str. If x is not # present, then it is going to store 0. count = [ 0 ] * MAX_CHAR # index[x] is going to store index of # character 'x' in str. If x is not # present or x is repeating, then it # is going to store a value (for example, # length of string) that cannot be a valid # index in str[] index = [ 0 ] * MAX_CHAR # Initialize counts of all characters # and indexes of non-repeating characters. for i in range ( MAX_CHAR): count[i] = 0 index[i] = n # A value more than any # index in str[] # Traverse the input string for i in range (n): # Find current character and # increment its count x = str [i] count[ ord (x)] + = 1 # If this is first occurrence, then # set value in index as index of it. if (count[ ord (x)] = = 1 ): index[ ord (x)] = i # If character repeats, then remove # it from index[] if (count[ ord (x)] = = 2 ): index[ ord (x)] = n # Sort index[] in increasing order. This step # takes O(1) time as size of index is 256 only index.sort() # After sorting, if index[k-1] is value, # then return it, else return -1. return index[k - 1 ] if (index[k - 1 ] ! = n) else - 1 # Driver code if __name__ = = "__main__" : str = "geeksforgeeks" k = 3 res = kthNonRepeating( str , k) if (res = = - 1 ): print ( "There are less than k" , "non-repeating characters" ) else : print ( "k'th non-repeating character is" , str [res]) # This code is contributed # by ChitraNayal |
C#
// C# program to find k'th non-repeating // character in a string using System; class GFG { public static int MAX_CHAR = 256; // Returns index of k'th non-repeating // character in given string str[] static int kthNonRepeating(String str, int k) { int n = str.Length; // count[x] is going to store count of // character 'x' in str. If x is not // present, then it is going to store 0. int []count = new int [MAX_CHAR]; // index[x] is going to store index of // character 'x' in str. If x is not // present or x is repeating, then it // is going to store a value (for // example, length of string) that // cannot be a valid index in str[] int []index = new int [MAX_CHAR]; // Initialize counts of all characters // and indexes of non-repeating // characters. for ( int i = 0; i < MAX_CHAR; i++) { count[i] = 0; // A value more than any index // in str[] index[i] = n; } // Traverse the input string for ( int i = 0; i < n; i++) { // Find current character and // increment its count char x = str[i]; ++count[x]; // If this is first occurrence, // then set value in index as // index of it. if (count[x] == 1) index[x] = i; // If character repeats, then // remove it from index[] if (count[x] == 2) index[x] = n; } // Sort index[] in increasing order. // This step takes O(1) time as size // of index is 256 only Array.Sort(index); // After sorting, if index[k-1] is // value, then return it, else // return -1. return (index[k-1] != n) ? index[k-1] : -1; } // driver program public static void Main () { String str = "geeksforgeeks" ; int k = 3; int res = kthNonRepeating(str, k); Console.Write(res == -1 ? "There are less" + " than k non-repeating characters" : "k'th non-repeating character is " + str[res]); } } // This code is contributed by nitin mittal. |
Javascript
<script> // Javascript program to find k'th non-repeating character // in a string let MAX_CHAR = 256; // Returns index of k'th non-repeating character in // given string str[] function kthNonRepeating(str,k) { let n = str.length; // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. let count = new Array(MAX_CHAR); // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] let index = new Array(MAX_CHAR); // Initialize counts of all characters and indexes // of non-repeating characters. for (let i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (let i = 0; i < n; i++) { // Find current character and increment its // count let x = str[i]; ++count[x.charCodeAt(0)]; // If this is first occurrence, then set value // in index as index of it. if (count[x.charCodeAt(0)] == 1) index[x.charCodeAt(0)] = i; // If character repeats, then remove it from // index[] if (count[x.charCodeAt(0)] == 2) index[x.charCodeAt(0)] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only (index).sort( function (a,b){ return a-b;}); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k-1] != n)? index[k-1] : -1; } // driver program let str = "geeksforgeeks" ; let k = 3; let res = kthNonRepeating(str, k); document.write(res == -1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + str[res]); // This code is contributed by ab2127 </script> |
k'th non-repeating character is r
Time Complexity: O(m log m) , where m is the MAX_CHARS = 256
Auxiliary Space: O(m), where m is the MAX_CHARS = 256
The Standard Solution/Approach Using Map:
The Approach:
In this approach, we use a map(stl) to store all the occurrences of characters in the string and then return the K’th Non-repeating Character.
C++
#include <bits/stdc++.h> #include <iostream> using namespace std; int main() { // given string string s = "geeksforgeeks" ; int k = 2; // map for the mapping. map< char , int > mp; // mapping over the string. for ( auto it : s) mp[it]++; for ( auto it : mp) { if (it.second == 1) { --k; if (k == 0) { cout << "The K’th Non-repeating Character " "is : " << endl; cout << it.first << endl; // break after you get the correct output. break ; } } } // code by Sanket Gode. return 0; } |
Java
import java.util.HashMap; import java.util.Map; public class GFG { public static void main(String[] args) { // given string String s = "geeksforgeeks" ; int k = 2 ; // map for the mapping Map<Character, Integer> map = new HashMap<>(); // mapping over the string for ( char c : s.toCharArray()) { if (map.containsKey(c)) { map.put(c, map.get(c) + 1 ); } else { map.put(c, 1 ); } } for (Map.Entry<Character, Integer> entry : map.entrySet()) { if (entry.getValue() == 1 ) { k--; if (k == 0 ) { System.out.println( "The Kth Non-repeating Character is :" ); System.out.println(entry.getKey()); // break after you get the correct // output break ; } } } } } // This code is contributed by Prasad Kandekar(prasad264) |
Python3
# given string s = "geeksforgeeks" k = 2 # dictionary for mapping mp = {} # mapping over the string for char in s: if char in mp: mp[char] + = 1 else : mp[char] = 1 for char in s: if mp[char] = = 1 : k - = 1 if k = = 0 : print ( "The K’th Non-repeating Character is:" ) print (char) # break after you get the correct output break # This code is contributed by Prasad Kandekar(prasad264) |
C#
using System; using System.Collections.Generic; public class GFG { static void Main( string [] args) { // given string string s = "geeksforgeeks" ; int k = 2; // dictionary for the mapping Dictionary< char , int > dict = new Dictionary< char , int >(); // mapping over the string foreach ( char c in s) { if (dict.ContainsKey(c)) { dict++; } else { dict = 1; } } foreach (KeyValuePair< char , int > entry in dict) { if (entry.Value == 1) { k--; if (k == 0) { Console.WriteLine( "The Kth Non-repeating Character is :" ); Console.WriteLine(entry.Key); // break after you get the correct // output break ; } } } } } // This code is contributed by Prasad Kandekar(prasad264) |
Javascript
//given string var s = "geeksforgeeks" ; var k = 2; //map for the mapping. var mp = {}; //mapping over the string. for ( var i=0; i<s.length; i++){ if (mp[s[i]] === undefined) mp[s[i]] = 1; else mp[s[i]]++; } for ( var key in mp){ if (mp[key] === 1){ k--; if (k === 0){ console.log( "The Kth Non-repeating Character is : " ); console.log(key); break ; } } } // This code is contributed by Prasad Kandekar(prasad264) |
The K’th Non-repeating Character is : o
Time Complexity: O(n), For Traversing.
Space Complexity: O(n), For Mapping.
Space Optimized Solution :
This can be space optimized and can be solved using a single index array only. Below is the space-optimized solution:
C++
#include <bits/stdc++.h> using namespace std; #define MAX_CHAR 256 int kthNonRepeating(string input, int k) { int inputLength = input.length(); /* * indexArr will store index of non-repeating * characters, inputLength for characters not in input * and inputLength+1 for repeated characters. */ int indexArr[MAX_CHAR]; // initialize all values in indexArr as inputLength. for ( int i = 0; i < MAX_CHAR; i++) { indexArr[i] = inputLength; } for ( int i = 0; i < inputLength; i++) { char c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } sort(indexArr, indexArr + MAX_CHAR); return (indexArr[k - 1] != inputLength) ? indexArr[k - 1] : -1; } int main() { string input = "geeksforgeeks" ; int k = 3; int res = kthNonRepeating(input, k); if (res == -1) cout << "There are less than k non-repeating " "characters" ; else cout << "k'th non-repeating character is " << input[res]; return 0; } // This code is contributed by gauravrajput1 |
Java
import java.util.*; public class GFG { public static int MAX_CHAR = 256 ; public static void main (String[] args) { final String input = "geeksforgeeks" ; int k = 3 ; int res = kthNonRepeating(input, k); System.out.println(res == - 1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + input.charAt(res)); } public static int kthNonRepeating( final String input, final int k) { final int inputLength = input.length(); /* * indexArr will store index of non-repeating characters, * inputLength for characters not in input and * inputLength+1 for repeated characters. */ final int [] indexArr = new int [MAX_CHAR]; // initialize all values in indexArr as inputLength. Arrays.fill(indexArr, inputLength); for ( int i = 0 ; i < inputLength ; i++) { final char c = input.charAt(i); if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2 ; } } Arrays.sort(indexArr); return (indexArr[k- 1 ] != inputLength) ? indexArr[k- 1 ] : - 1 ; } } // Contributed by AK |
Python3
MAX_CHAR = 256 def kthNonRepeating( Input ,k): inputLength = len ( Input ) # indexArr will store index of non-repeating characters, # inputLength for characters not in input and # inputLength+1 for repeated characters. # initialize all values in indexArr as inputLength. indexArr = [inputLength for i in range (MAX_CHAR)] for i in range (inputLength): c = Input [i] if (indexArr[ ord (c)] = = inputLength): indexArr[ ord (c)] = i else : indexArr[ ord (c)] = inputLength + 2 indexArr.sort() if (indexArr[k - 1 ] ! = inputLength): return indexArr[k - 1 ] else : return - 1 Input = "geeksforgeeks" k = 3 res = kthNonRepeating( Input , k) if (res = = - 1 ): print ( "There are less than k non-repeating characters" ) else : print ( "k'th non-repeating character is" , Input [res]) # This code is contributed by rag2127 |
C#
using System; public class GFG { public static int MAX_CHAR = 256; static public void Main () { string input = "geeksforgeeks" ; int k = 3; int res = kthNonRepeating(input, k); Console.WriteLine(res == -1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + input[res]); } public static int kthNonRepeating( string input, int k) { int inputLength = input.Length; /* * indexArr will store index of non-repeating characters, * inputLength for characters not in input and * inputLength+1 for repeated characters. */ int [] indexArr = new int [MAX_CHAR]; // initialize all values in indexArr as inputLength. Array.Fill(indexArr, inputLength); for ( int i = 0; i < inputLength ; i++) { char c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } Array.Sort(indexArr); return (indexArr[k - 1] != inputLength) ? indexArr[k - 1] : -1; } } // This code is contributed by avanitrachhadiya2155 |
Javascript
<script> let MAX_CHAR = 256; function kthNonRepeating(input, k) { let inputLength = input.length; /* * indexArr will store index of non-repeating characters, * inputLength for characters not in input and * inputLength+1 for repeated characters. */ let indexArr = new Array(MAX_CHAR); // initialize all values in indexArr as inputLength. for (let i=0;i<MAX_CHAR;i++) { indexArr[i]=inputLength; } for (let i = 0; i < inputLength ; i++) { let c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } (indexArr).sort( function (a,b){ return a-b;}); return (indexArr[k-1] != inputLength) ? indexArr[k-1] : -1; } let input = "geeksforgeeks" ; let k = 3; let res = kthNonRepeating(input, k); document.write(res == -1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + input[res]); // This code is contributed by unknown2108 </script> |
k'th non-repeating character is r
Time Complexity: O(m log m) , where m is the MAX_CHARS = 256
Auxiliary Space: O(m), where m is the MAX_CHARS = 256
This article is contributed by Aarti_Rathi and Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
Please Login to comment...