Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
K’th Non-repeating Character in Python
Next article icon

K’th Non-repeating Character in Python

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 can be done using multiple functions list comprehension and many other function.

Using OrderedDict and List Comprehension

Solution uses OrderedDict to count character frequencies while maintaining their order of appearance. It then uses list comprehension to filter non-repeating characters and retrieves the K'th one if available.

Python
from collections import OrderedDict  s = "geeksforgeeks" k = 3  # Count frequency of each character using OrderedDict freq = OrderedDict() for char in s:     freq[char] = freq.get(char, 0) + 1  # Use list comprehension to filter non-repeating characters a = [char for char, count in freq.items() if count == 1]  # Return the K'th non-repeating character if k <= len(a):     print(a[k - 1])  else:     print(None) 

Output
r 

Explanatinon:

  • Code uses an OrderedDict to count the frequency of each character in the string s while maintaining the order of their first occurrence.
  • It filters the non-repeating characters using list comprehension and then checks if there are enough non-repeating characters to return the K'th one; if so, it prints it, otherwise prints None.

Using a Regular Dictionary and List Comprehension

Solution uses a regular dictionary to count character frequencies while iterating through the string. List comprehension then filters out non-repeating characters, allowing retrieval of the K'th non-repeating character if available.

Python
s = "geeksforgeeks" k = 3  # Count frequency of each character using a regular dictionary freq = {} for char in s:     freq[char] = freq.get(char, 0) + 1  # Use list comprehension to filter non-repeating characters a = [char for char in s if freq[char] == 1]  # Return the K'th non-repeating character if k <= len(a):     print(a[k - 1])   else:     print(None) 

Output
r 

Explanation:

  • Code counts the frequency of each character in the string s using a regular dictionary and then filters out the non-repeating characters by checking the frequency of each character.
  • It then checks if the list of non-repeating characters has enough elements to return the K'th non-repeating character, printing it if available, or None otherwise.

Using a Single Loop

Solution counts character frequencies and extracts non-repeating characters in a single loop, maintaining the order of their appearance. It then checks if there are enough non-repeating characters to return the K'th one.

Python
s = "geeksforgeeks" k = 3  # Create a dictionary to store the frequency of each character freq = {}  # First pass: Count frequency of each character for char in s:     freq[char] = freq.get(char, 0) + 1  # Second pass: Find non-repeating characters a = [] for char in s:     if freq[char] == 1:         a.append(char)  # Return the K'th non-repeating character if k <= len(a):     print(a[k - 1])  # Output: 'r' else:     print(None) 

Output
r 

Explanation:

  • Code performs two passes: in the first pass, it counts the frequency of each character in the string s using a dictionary in the second pass, it iterates through the string again to collect non-repeating characters.
  • It checks if there are enough non-repeating characters to return the K'th one, printing it if available, or None if the list is too short

Using collections.Counter

Solution uses collections.Counter to count the frequency of each character in the string. It then filters out non-repeating characters using list comprehension and retrieves the K'th non-repeating character if available

Python
from collections import Counter  s = "geeksforgeeks" k = 3  # Count frequency of characters using Counter freq = Counter(s)  # Extract non-repeating characters a = [char for char in s if freq[char] == 1]  # Return the K'th non-repeating character if k <= len(a):     print(a[k - 1])  # Output: 'r' else:     print(None) 

Output
r 

Explanation:

  • Code uses Counter from the collections module to count the frequency of each character in the string s.
  • It then extracts the non-repeating characters using a list comprehension and checks if there are enough non-repeating characters to return the K'th one, printing it if available or None otherwise.

Next Article
K’th Non-repeating Character in Python

S

Shashank Mishra (Gullu)
Improve
Article Tags :
  • Strings
  • Python
  • DSA
  • python-list
  • python-dict
  • Python list-programs
  • Python dictionary-programs
Practice Tags :
  • python
  • python-dict
  • python-list
  • Strings

Similar Reads

    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 = 2O
    14 min read
    Find the Earliest Repeating Character
    Given a string S of length n, the task is to find the earliest repeated character in it. The earliest repeated character means, the character that occurs more than once and whose second occurrence has the smallest index.Example:Input: s = "geeksforgeeks" Output: e Explanation: e is the first element
    9 min read
    Count K-Length Substrings With No Repeated Characters
    Given a string S and an integer k, the task is to return the number of substrings in S of length k with no repeated characters.Example:Input: S = "geeksforgeeks", k = 5Output: 4Explanation: There are 4 substrings, they are: 'eksfo', 'ksfor', 'sforg', 'forge'.Input: S = "home", k = 5Output: 0Explanat
    6 min read
    Python Dictionary to find mirror characters in a string
    Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on. Examples: Input : N = 3 paradox Output : paizwlc We mirror characters from position 3 to end.
    2 min read
    Count the number of Unique Characters in a String in Python
    We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8.Using setSet in Python is an unordered collection of unique elements automatically removing du
    2 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