What does it solve?
Return the index of the first character in a string that appears exactly once, or −1 if none does. The answer is an index, not the character, so order matters.
Key insight: this is index mapping in two passes. First, tally each character's frequency in a map. Then walk the string again in order and return the position of the first char whose count is 1. Because the second pass respects the original indices, you get the earliest one for free. Counting and scanning are each O(N) → O(N) overall.
The core idea
count = {}
for c in s: count[c]++
for i, c in enumerate(s):
if count[c] == 1:
return i
return −1
Complexity
Two linear passes: one to build the frequency map, one to find the first count-of-one index. No sorting, no nested loops.
K distinct characters in the map. For lowercase letters that's at most 26, so effectively O(1).
Examples & edge cases
Step-by-step table
C++ implementation
#include <bits/stdc++.h> using namespace std; // Index of the first character that appears exactly once, else -1 int firstUniqChar(string s) { int count[26] = {}; // pass 1: tally frequencies for (char c : s) count[c - 'a']++; // pass 2: first index whose char has count 1 for (int i = 0; i < (int)s.size(); i++) if (count[s[i] - 'a'] == 1) return i; return -1; } int main() { cout << firstUniqChar("leetcode") << "\n"; // 0 cout << firstUniqChar("loveleetcode") << "\n"; // 2 cout << firstUniqChar("aabb") << "\n"; // -1 return 0; }
My Notes