#387

First Unique Character in a String

Easy
Hash TableStringQueueCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a hash map to count occurrences of each character in one pass, then checks for the first unique character in another pass. This is efficient and reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hash map to store character counts.
  2. 2Step 2: Loop through the string and populate the hash map with character counts.
  3. 3Step 3: Loop through the string again to find the first character with a count of 1.
  4. 4Step 4: Return the index of that character or -1 if none exists.
solution.py8 lines
1def firstUniqChar(s):
2    count = {}
3    for char in s:
4        count[char] = count.get(char, 0) + 1
5    for i in range(len(s)):
6        if count[s[i]] == 1:
7            return i
8    return -1

Complexity note: The time complexity is O(n) because we traverse the string twice (once for counting and once for finding the unique character). Space complexity is O(n) due to the hash map storing character counts.

  • 1Using a hash map allows for efficient counting of characters.
  • 2Two passes through the string are often needed for counting and checking.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.