Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
K'th Non-repeating Character
Next article icon

Find the last non repeating character in string

Last Updated : 15 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 the 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 that will store the frequency of each of the characters 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 a frequency greater than 1 then print -1.
Below is the implementation of the above approach:
 

C++
// C++ implementation of the approach #include <bits/stdc++.h>  using namespace std;  // Maximum distinct characters possible const 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[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 code int main()  {     string str = "GeeksForGeeks";     int n = str.size();     cout<< lastNonRepeating(str, n);     return 0; }  // This code has been contributed by 29AjayKumar 
Java
// Java implementation of the approach public 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
# Python3 implementation of the approach   # Maximum distinct characters possible  MAX = 256;   # Function to return the last non-repeating character  def 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 code  if __name__ == "__main__" :           string = "GeeksForGeeks";      n = len(string);           print(lastNonRepeating(string, n));   # This code is contributed by AnkitRai01 
C#
// C# implementation of the approach using 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 */ 
JavaScript
function lastNonRepeating(str, n) {     // Maximum distinct characters possible     const MAX = 256;      // To store the frequency of each of     // the character of the given string     const freq = new Array(MAX).fill(0);      // Update the frequencies     for (let i = 0; i < n; i++)         freq[str.charCodeAt(i)]++;      // Starting from the last character     for (let i = n - 1; i >= 0; i--) {         // Current character         const ch = str.charAt(i);          // If frequency of the current character is 1         // then return the character         if (freq[ch.charCodeAt()] == 1) return ch;     }      // All the characters of the     // string are repeating     return "-1"; }  const str = "GeeksForGeeks"; const n = str.length; console.log(lastNonRepeating(str, n)); 

Output: 
r

 

Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(256) ? O(1), no extra space is required, so it is a constant.


Next Article
K'th Non-repeating Character
author
29AjayKumar
Improve
Article Tags :
  • Strings
  • Technical Scripter
  • DSA
  • frequency-counting
Practice Tags :
  • Strings

Similar Reads

  • First non-repeating character of given string
    Given a string s of lowercase English letters, the task is to find the first non-repeating character. If there is no such character, return '$'. Examples: Input: s = "geeksforgeeks"Output: 'f'Explanation: 'f' is the first character in the string which does not repeat. Input: s = "racecar"Output: 'e'
    9 min read
  • First non-repeating character in a stream
    Given an input stream s consisting solely of lowercase letters, you are required to identify which character has appeared only once in the stream up to each point. If there are multiple characters that have appeared only once, return the one that first appeared. If no character has appeared only onc
    15+ min read
  • Find repeated character present first in a string
    Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) Examples: Input : geeksforgeeks Output : g (mind that it will be g, not e.) Asked in: Goldman Sachs internship Simple Solution using O(N^2) complexity: The solution is to loop thro
    15 min read
  • K’th Non-repeating Character in Python
    We need to find the first K characters in a string that do not repeat within the string. This involves identifying unique characters and their order of appearance. We are given a string s = "geeksforgeeks" we need to return the non repeating character from the string which is 'r' in this case. This
    4 min read
  • K'th Non-repeating Character
    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 = 3Output : rExplanation: First non-repeating character is f, second is o and third is r. Input : str = geeksforgeeks, k =
    14 min read
  • Queries to find the last non-repeating character in the sub-string of a given string
    Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the last non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks", q[] = {{2, 9}, {2, 3}
    11 min read
  • Print Longest substring without repeating characters
    Given a string s having lowercase characters, find the length of the longest substring without repeating characters. Examples: Input: s = “geeksforgeeks”Output: 7 Explanation: The longest substrings without repeating characters are “eksforg” and “ksforge”, with lengths of 7. Input: s = “aaa”Output:
    14 min read
  • Longest Substring Without Repeating Characters
    Given a string s having lowercase characters, find the length of the longest substring without repeating characters. Examples: Input: s = "geeksforgeeks"Output: 7 Explanation: The longest substrings without repeating characters are "eksforg” and "ksforge", with lengths of 7. Input: s = "aaa"Output:
    12 min read
  • Print the frequency of adjacent repeating characters in given string
    Given a string str of length N. The task is to print the frequency of adjacent repeating characters. Examples: Input: str = "Hello"Output: l: 2Explanation: Consecutive Repeating Character from the given string is "l" and its frequency is 2. Input: str = "Hellolllee"Output: l: 2 l: 3 e: 2Explanation:
    5 min read
  • Print the first and last character of each word in a String
    Given a string s consisting of multiple words, print the first and last character of each word. If a word contains only one character, print it twice (since the first and last characters are the same).Note: The string will not contain leading or trailing spaces. Examples: Input: s = "Geeks for geeks
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences