💡
Exercise 25

First Unique Character 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

LeetCode #387: First Unique Character in a String

Given a string s, find the first non-repeating character and return its index. If it doesn't exist, return -1.

Approach: Two passes — first count all characters, then find the first with count 1.

💭 Challenge time! Now implement this yourself using the strategy above. The best way to learn is by doing! ⭐

Complexity: Time O(n), Space O(1) — at most 26 chars.

📋 Instructions
Implement `firstUniqChar(s)` using the two-pass approach. - First pass: count character frequencies - Second pass: return index of first character with count 1 - Return -1 if all characters repeat
Create count = {}. First loop: for c in s: count[c] = count.get(c, 0) + 1. Second loop: for i, c in enumerate(s): if count[c] == 1: return i. After loop: return -1.
⚠️ Try solving it yourself first — you'll learn more!
def firstUniqChar(s):
    count = {}
    # Pass 1: Count frequencies
    for c in s:
        count[c] = count.get(c, 0) + 1
    # Pass 2: Find first with count == 1
    for i, c in enumerate(s):
        if count[c] == 1:
            return i
    return -1
🧪 Test Cases
Input
firstUniqChar("leetcode")
Expected
0
Boundary value
Input
firstUniqChar("loveleetcode")
Expected
2
Test case 2
Input
firstUniqChar("aabb")
Expected
-1
Boundary value
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.