QuestionsDSA

First Unique Character

Hash Map / SetEasyDSA

Return the index of the first non-repeating character in a string, or -1 if none.

What it tests

Frequency counting — and knowing that objects/Maps give O(1) tallying.

Approach & answer

Two passes: first tally every character's count, then scan again and return the first with count 1. Two passes is still O(n) and beats re-counting inside a loop (which would be O(n²)). The key insight is that 'first' requires original order, so you can't just look at the frequency map alone — you re-walk the string in order and consult the tally. A single-pass alternative stores {count, firstIndex} per char, but two clean passes are simpler and just as fast asymptotically.

Use this technique when

Any 'first/only/most frequent element' question → build a frequency map first.

Complexity

Time O(n) · Space O(k) where k = distinct chars

References

js