LeetCode / Classic Index Mapping Easy

First Unique Character in a String

LC
Practice this algorithm on LeetCode to reinforce your understanding.
Open Problem

Count every character in one pass, then map back to the first index whose count is exactly one — O(N) time

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

// pass 1: count, pass 2: map to index
count = {}
for c in s: count[c]++
for i, c in enumerate(s):
  if count[c] == 1:
    return i
return −1

Complexity

Time complexity
O(N)

Two linear passes: one to build the frequency map, one to find the first count-of-one index. No sorting, no nested loops.

Space complexity
O(K)

K distinct characters in the map. For lowercase letters that's at most 26, so effectively O(1).


Examples & edge cases

Live animation — count, then map to the first unique index
String s
Frequency map — character → count
{ } empty
Current step detail
i = — char = — count = — answer = —
Step — of —
index i
—
position
current char
—
s[i]
distinct chars
—
in the map
answer index
—
first unique
Pick a phase and press Play to start.
✓ Done
Speed Medium

Step-by-step table

C++ implementation

first_unique_char.cpp
#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

📝 Notes ✅

▼