
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
Editorial
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. |
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