First Unique Character in a String

Return the index of the first non-repeating character, or -1.

Easy
Time O(N) Space O(1)
LeetCode
3 min read
hash-map counting strings

Problem#

Given a string s of lowercase letters, return the index of the first character that appears exactly once, or -1.

Examples#

  • "leetcode"0.
  • "loveleetcode"2.
  • "aabb"-1.

Constraints#

  • 1 <= s.length <= 10^5.

Hints#

Hint
Count first, scan second — first index where count is 1 is the answer.

Approach#

Two passes. First pass tally counts; second pass returns the first index with count 1.

Solution#

First Unique Character in a String
class Solution {
public:
int firstUniqChar(string s) {
int cnt[26] = {0};
for (char c : s) ++cnt[c - 'a'];
for (int i = 0; i < (int)s.size(); ++i) if (cnt[s[i] - 'a'] == 1) return i;
return -1;
}
};

Editorial#

Two passes are necessary because uniqueness is only known after seeing the whole string. Using int[26] keeps memory tight; the scan is O(N). A streaming version (one pass) is possible with a doubly-linked list of indices but complicates the code without complexity gains for this problem size.

Complexity#

  • Time: O(N).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.