JavaScript Program to Find K’th Non-Repeating Character in String

The K’th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K’th unique character encountered, it is returned as the result. This operation helps identify the K’th non-repeating character in the string. In this article, we will find K’th Non-repeating Character in a string using JavaScript.

Examples :

Input: s = 'w3wiki' , K = 2
Output: o
Explanation: In the given string, the 2nd non-repeating character is 'o' because 'f' is the first
character that appears only once and 'o' is the next character following it.

Input: 'javascript', K = 4
Output: c
Explanation: In the given string, the 4th non-repeating character is 'c' as 'j', 'v', and 's' are the characters
that appears only once and 'c' is the next character following it.

Table of Content

  • Method 1: Brute Force approach
  • Method 2: Using Hashmap
  • Method 3: Using Map
  • Method 4: Using Queue

Method 1: Brute Force approach

As a brute force solution, use nested loops to traverse through the string. Starting from the first element, check for every character whether it repeats or not. Use a counter to keep a count of unique elements. When the count reaches K, return the character.

Algorithm:

  • Iterate the string from left character by character.
  • For each element in the outer loop, keep a check if the character is repeating in the inner loop.
  • Initialize a flag to check for the repeating character.
  • If the character does not repeat, increment the counter.
  • Whenever the count reaches K, return the current character as our answer.
  • If Kth non-repeating character is not found, return null which indicates that the character does not exist.

Example: In this code we will find K’th Non-repeating Character in string with brute force approach.

Javascript
function kthNonRepeating(s, K) {
    const n = s.length;
    let cnt = 0, ans = null;

    for (let i = 0; i < n; i++) {
        let flag = 0;
        for (let j = i + 1; j < n; j++) {
            if (s[i] == s[j]) {
                flag = 1;
                break;
            }
        }

        if (!flag) {
            cnt++;
            if (cnt == K) {
                ans = s[i];
                break;
            }
        }
    }
    return ans;
}

let s = "w3wiki";
let K = 3;

let res = kthNonRepeating(s, K);

if (res == null) {
    console.log(-1);
}
else {
    console.log(res);
}

Output
r

Time Complexity: O(N2)

Auxiliary Space: O(1)

Method 2: Using Hashmap

Store the character frequency in a hashmap. Then iterate through the string an find the appropriate character whose frequency is 1 and return the Kth element.

Algorithm:

  • Create a map to store the count of the characters.
  • Iterate through the string and update their frequencies respectively.
  • Again traverse through the string.
  • If frequency of the character is 1, decrement the value of K.
  • Once the value of K reaches 0, return the current character.

Example: In this code we will find K’th Non-repeating Character in string by using hashmap approach.

Javascript
function KthNonRepeatingChar(s, K) {
    const n = s.length;
    
    // Create a map
    let mp = {};
    let ans = null;

    // Iterate through the string
    for (let i = 0; i < n; i++) {
        let ch = s[i];
        if (mp[ch] == undefined) {
            mp[ch] = 1;
        }
        else {
            mp[ch]++;
        }
    }
    
    // Iterate through the string again 
    // and find the Kth non-repeating character
    for (let i = 0; i < n; i++) {
        let ch = s[i];
        if (mp[ch] == 1) {
            K--;
            if (K == 0) {
                ans = ch;
            }
        }
    }

    return ans;
}


let s = "w3wiki";
const K = 3;

// Function call
let ans = KthNonRepeatingChar(s, K);
console.log(ans);

Output
r

Time Complexity: O(n)

Auxiliary Space: O(1)

Method 3: Using Map

This approach employs a Map data structure to efficiently count the occurrences of each character in the string. By utilizing a map, we can achieve a linear time complexity solution.

Algorithm:

  1. Create a Map to store the count of occurrences of each character in the string.
  2. Iterate through the string, updating the counts in the map accordingly.
  3. Traverse the string again, checking for the K’th non-repeating character based on the counts stored in the map.
  4. If the K’th non-repeating character is found, return it; otherwise, return null.

Example:

JavaScript
function findKthNonRepeating(s, K) {
    const charCounts = new Map();
    
    // Count occurrences of each character
    for (const char of s) {
        charCounts.set(char, (charCounts.get(char) || 0) + 1);
    }
    
    // Find the K'th non-repeating character
    let count = 0;
    for (const char of s) {
        if (charCounts.get(char) === 1) {
            count++;
            if (count === K) {
                return char;
            }
        }
    }
    
    // If K'th non-repeating character not found, return null
    return null;
}

const s = "w3wiki";
const K = 3;

const result = findKthNonRepeating(s, K);
console.log(result); // Output: r

Output
r

Time Complexity: O(n)

Auxiliary Space: O(n)

Method 4: Using Queue

This approach utilizes a queue to keep track of the order of characters as they appear and their frequency. This method leverages the properties of a queue (FIFO) to efficiently find the K’th non-repeating character.

Algorithm:

  • Create a frequency map to store the count of each character.
  • Create a queue to keep track of characters and their positions in the string.
  • Traverse the string and update the frequency map and queue.
  • Process the queue to find the K’th non-repeating character.

Here’s the implementation in JavaScript:

JavaScript
function findKthNonRepeatingUsingQueue(s, K) {
    const freqMap = new Map();
    const queue = [];

    // Populate the frequency map and queue
    for (let i = 0; i < s.length; i++) {
        const char = s[i];
        if (!freqMap.has(char)) {
            freqMap.set(char, 1);
            queue.push(char);
        } else {
            freqMap.set(char, freqMap.get(char) + 1);
        }
    }

    // Process the queue to find the K'th non-repeating character
    let count = 0;
    while (queue.length > 0) {
        const char = queue.shift();
        if (freqMap.get(char) === 1) {
            count++;
            if (count === K) {
                return char;
            }
        }
    }

    // If K'th non-repeating character not found, return null
    return null;
}

const s = "w3wiki";
const K = 3;

const result = findKthNonRepeatingUsingQueue(s, K);
console.log(result); // Output: r

Output
r




Contact Us