Find the last non repeating character in string - GeeksforGeeks

03 Jun, 2021
Given a string str, the task is to find the last non-repeating character in it. For example, if the input string is “GeeksForGeeks”, then the output should be ‘r’ and if input string is “GeeksQuiz” then the output should be ‘z’. if there is no non-repeating character then print -1.Examples:  
Input: str = “GeeksForGeeks” Output: r ‘r’ is the first character from the end which has frequency 1.Input: str = “aabbcc” Output: -1 All the characters of the given string have frequencies greater than 1.  
 
Approach: Create a frequency array which will store the frequency of each of the character of the given string. Once the frequencies have been updated, start traversing the string from the end character by character and for every character, if the frequency of the current character is 1 then this is the last non-repeating character. If all the characters have frequency greater than 1 then print -1.Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Maximum distinct characters possibleconst int MAX = 256; // Function to return the last non-repeating characterstatic string lastNonRepeating(string str, int n){     // To store the frequency of each of    // the character of the given string    int freq[MAX] = {0};     // Update the frequencies    for (int i = 0; i < n; i++)        freq[str.at(i)]++;          // Starting from the last character    for (int i = n - 1; i >= 0; i--)    {         // Current character        char ch = str.at(i);         // If frequency of the current character is 1        // then return the character        if (freq[ch] == 1)        {            string res;            res+=ch;            return res;        }    }     // All the characters of the    // string are repeating    return "-1";} // Driver codeint main(){    string str = "GeeksForGeeks";    int n = str.size();    cout<< lastNonRepeating(str, n);    return 0;} // This code has been contributed by 29AjayKumar
// Java implementation of the approachpublic class GFG {     // Maximum distinct characters possible    static final int MAX = 256;     // Function to return the last non-repeating character    static String lastNonRepeating(String str, int n)    {         // To store the frequency of each of        // the character of the given string        int freq[] = new int[MAX];         // Update the frequencies        for (int i = 0; i < n; i++)            freq[str.charAt(i)]++;         // Starting from the last character        for (int i = n - 1; i >= 0; i--) {             // Current character            char ch = str.charAt(i);             // If frequency of the current character is 1            // then return the character            if (freq[ch] == 1)                return ("" + ch);        }         // All the characters of the        // string are repeating        return "-1";    }     // Driver code    public static void main(String[] args)    {        String str = "GeeksForGeeks";        int n = str.length();        System.out.println(lastNonRepeating(str, n));    }}
# Python3 implementation of the approach # Maximum distinct characters possibleMAX = 256; # Function to return the last non-repeating characterdef lastNonRepeating(string, n) :     # To store the frequency of each of    # the character of the given string    freq = [0]*MAX;     # Update the frequencies    for i in range(n) :        freq[ord(string[i])] += 1;     # Starting from the last character    for i in range(n-1,-1,-1) :         # Current character        ch = string[i];         # If frequency of the current character is 1        # then return the character        if (freq[ord(ch)] == 1) :            return ("" + ch);          # All the characters of the    # string are repeating    return "-1";  # Driver codeif __name__ == "__main__" :         string = "GeeksForGeeks";    n = len(string);         print(lastNonRepeating(string, n)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;     class GFG{     // Maximum distinct characters possible    static readonly int MAX = 256;     // Function to return the last non-repeating character    static String lastNonRepeating(String str, int n)    {         // To store the frequency of each of        // the character of the given string        int []freq = new int[MAX];         // Update the frequencies        for (int i = 0; i < n; i++)            freq[str[i]]++;         // Starting from the last character        for (int i = n - 1; i >= 0; i--)        {             // Current character            char ch = str[i];             // If frequency of the current character is 1            // then return the character            if (freq[ch] == 1)                return ("" + ch);        }         // All the characters of the        // string are repeating        return "-1";    }     // Driver code    public static void Main(String[] args)    {        String str = "GeeksForGeeks";        int n = str.Length;        Console.WriteLine(lastNonRepeating(str, n));    }} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript implementation of the approach          // Maximum distinct characters possible    let MAX = 256;         // Function to return the last non-repeating character    function lastNonRepeating(str,n)    {        // To store the frequency of each of        // the character of the given string        let freq = new Array(MAX);          for(let i=0;i<MAX;i++)        {            freq[i]=0;        }        // Update the frequencies        for (let i = 0; i < n; i++)            freq[str[i].charCodeAt(0)]++;           // Starting from the last character        for (let i = n - 1; i >= 0; i--) {               // Current character            let ch = str[i];               // If frequency of the current character is 1            // then return the character            if (freq[ch.charCodeAt(0)] == 1)                return ("" + ch);        }           // All the characters of the        // string are repeating        return "-1";    }         // Driver code    let str = "GeeksForGeeks";    let n = str.length;    document.write(lastNonRepeating(str, n));  // This code is contributed by rag2127 </script>
r
 
princiraj1992
ankthon
29AjayKumar
rag2127
frequency-counting
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Naive algorithm for Pattern Searching
Vigenère Cipher
How to Append a Character to a String in C
Convert character array to string in C++
sprintf() in C
Reverse words in a given String in Python
Converting Roman Numerals to Decimal lying between 1 to 3999
Iterate over characters of a string in C++