Tutorialspoint
Problem
Solution
Submissions

Find the First Non-Repeating Character in a String

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 5

Write a Python program that finds the first non-repeating character in a string.

Example 1
  • Input: "leetcode"
  • Output: 'l'
  • Explanation:
    • Step 1: Take the input string "leetcode".
    • Step 2: The first character 'l' only appears once in the string.
    • Step 3: Return 'l' as the result.
Example 2
  • Input: "loveleetcode"
  • Output: 'v'
  • Explanation:
    • Step 1: Take the input string "loveleetcode".
    • Step 2: The characters 'l', 'o', 'v', 'e' appear in order, but 'l' and 'e' appear multiple times.
    • Step 3: The first character that appears only once is 'v'.
    • Step 4: Return 'v' as the result.
Constraints
  • 1 ≤ len(s) ≤ 10^5
  • String contains only lowercase English letters
  • Time Complexity: O(n)
  • Space Complexity: O(1)
StringsDictionaries Tech Mahindra
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a dictionary to count the frequency of each character.
  • Iterate through the string to find the first character with a count of 1.
  • Use the collections.Counter class for efficient counting.

Steps to solve by this approach:

 Step 1: Import Counter from the collections module.
 Step 2: Create a Counter object to count occurrences of each character in the string.
 Step 3: Iterate through each character in the original string (preserving order).
 Step 4: For each character, check if its count is exactly 1.
 Step 5: Return the first character that has a count of 1 (non-repeating).
 Step 6: If no non-repeating character exists, return None.
 Step 7: Example: In "leetcode", 'l' is the first non-repeating character.

Submitted Code :