Tutorialspoint
Problem
Solution
Submissions

First Unique Character

Certification: Basic Level Accuracy: 50% Submissions: 2 Points: 5

Write a JavaScript program to find the first non-repeating character in a string and return its index. If no such character exists, return -1. The string contains only lowercase English letters.

Example 1
  • Input: s = "tutorialspoint"
  • Output: 1
  • Explanation: Character 't' at index 0 appears twice in the string. Character 'u' at index 1 appears only once in the string. The first unique character is 'u' at index 1.
Example 2
  • Input: s = "codepoint"
  • Output: 0
  • Explanation: Character 'C' appears at indices 0 appears only once in the string. The first unique character is 'c' at index 0.
Constraints
  • 1 ≤ s.length ≤ 10^5
  • s consists of only lowercase English letters
  • Time Complexity: O(n)
  • Space Complexity: O(1) since we only have 26 possible characters
  • Return -1 if no unique character exists
StringsWalmartOracle
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 hash map or array to count the frequency of each character
  • Make two passes through the string - first to count, second to find
  • In the first pass, count the frequency of each character
  • In the second pass, find the first character with frequency 1
  • Since only lowercase letters are used, you can use an array of size 26
  • Map characters to array indices using ASCII values
  • Return the index of the first character with count 1, or -1 if none exists

Steps to solve by this approach:

 Step 1: Create an array of size 26 to store frequency count of each lowercase letter.
 Step 2: Initialize all frequency counts to 0.
 Step 3: Make the first pass through the string to count frequency of each character.
 Step 4: Use ASCII value mapping to convert characters to array indices (a=0, b=1, etc.).
 Step 5: Make the second pass through the string to find the first character with frequency 1.
 Step 6: For each character, check its frequency in the count array.
 Step 7: Return the index of the first character with count 1, or -1 if no unique character exists.

Submitted Code :