Sweaty Imposter

First Unique Character in a String

EasyArrays & HashingNeetCode 150JuniorOpen on LeetCodeUpdated

You're given a string s of lowercase English letters. Find the first character, reading left to right, that appears exactly once in the whole string, and return its 0-based index. If every character appears more than once, return -1.

Examples

s = "leetcode" returns 0

The "l" at index 0 appears nowhere else, so it's the first unique character.

s = "loveleetcode" returns 2

"l" and "o" both appear twice, so indices 0 and 1 are out. The "v" at index 2 appears only once.

s = "aabb" returns -1

Both "a" and "b" appear twice, so no character is unique.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of only lowercase English letters.

Hints

Hint 1

You can't tell whether a character is unique until you've seen the whole string. What could you gather first?

Hint 2
A pointer toward the approach
Hint 3
The full approach, step by step

Drill This: Your Approach First

Approach

A character is unique only if it appears once in the whole string, so you can't decide during the first read. First count every letter in an array of 26 slots. Then walk s again from the left and return the first index whose letter has count 1, or -1 if none does. The count array has a fixed size, so extra space is constant.

Time

O(n)

Space

O(1)

Pitfall

The second pass must walk s in order, not the 26 letters of the alphabet, or you'll return the alphabetically first unique letter instead of the earliest one: for "cba" that gives 2 instead of 0.

Solutions

class Solution {
    public int firstUniqChar(String s) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) count[s.charAt(i) - 'a']++;
        for (int i = 0; i < s.length(); i++) {
            if (count[s.charAt(i) - 'a'] == 1) return i;
        }
        return -1;
    }
}
Drill This