First non-repeating character
Two passes. Count every character, then walk the string again and return the first with a count of one. One pass cannot do it — you cannot know a character is unique until you have seen the whole string. O(n) time, O(k) space.
Overview
Why one pass is impossible
Reading left to right, the first character might be unique or might repeat at the very end. Nothing can be returned until the whole string has been read, so a single pass that emits an answer as it goes is wrong by construction.
What a single pass can do is record enough to answer at the end — which is what the counter is. The second pass is not extra work in the complexity sense: two linear passes is still O(n).
Step through it
What to watch
- Pass one fills the counter; nothing is decided during it.
- Pass two returns at the first count of 1 — order comes from the string, not the dictionary.
swiss:wwins, becausesrepeats.
Say this out loud
"Count in one pass, then scan again for the first count of one. Two passes is O(n) - and you can't do it in one, because uniqueness isn't decidable until the end."