Tutorialspoint
Problem
Solution
Submissions

First Unique Character in a String

Certification: Basic Level Accuracy: 78.95% Submissions: 19 Points: 5

Write a Java program to find the first non-repeating character in a string and return its index. If it doesn't exist, return -1. You must examine each character in the string exactly once.

Example 1
  • Input: s = "greenarmy"
  • Output: 0
  • Explanation:
    • 'g' is the first character and occurs only once
Example 2
  • Input: s = "Tutorialspoint"
  • Output: 2
  • Explanation:
    • 't' appear more than once
    • 'u' is the first unique character
Constraints
  • 1 ≤ s.length ≤ 10^5
  • s consists of only lowercase English letters
  • Time Complexity: O(n)
  • Space Complexity: O(1) or O(k) where k is the character set size
StringsPwCD. E. Shaw
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 frequency counter to count the occurrences of each character
  • Iterate through the string once to populate the frequency counter
  • Iterate through the string again to find the first character with a frequency of 1
  • Return the index of that character
  • If no character has a frequency of 1, return -1

Steps to solve by this approach:

 Step 1: Create a frequency array of size 26 to store the count of each lowercase English letter.
 Step 2: Iterate through the string and increment the frequency count for each character.
 Step 3: For each character, calculate its index in the frequency array by subtracting 'a' from it.
 Step 4: After counting the frequency of all characters, iterate through the string again.
 Step 5: For each character, check if its frequency is 1 (meaning it appears only once).
 Step 6: If a character with frequency 1 is found, return its index in the string.
 Step 7: If no character has a frequency of 1, return -1 to indicate that there is no unique character.

Submitted Code :