↓Skip to main content
  1. LeetCode/

LeetCode 387: First Unique Character in a String

·1 min· ·
LeetCode Easy Hash-Table String Queue Counting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Runtime Error → Accepted ×2 → Wrong Answer → Accepted

Approach
#

Two passes (Hash Table Template 1): count every character with a Counter, then scan left to right for the first index whose count is 1. With 26 letters the space is O(1).

My Attempts
#

Attempt 1 was a syntax error; then a dict of characters appearing once, scanned left to right for the first member, passed. A later one-liner with OrderedDict(Counter(s)) took one WA to get right.

Solution
#

class Solution:
    def firstUniqChar(self, s: str) -> int:
        cnt = Counter(s)
        for i, c in enumerate(s):
            if cnt[c] == 1:
                return i
        return -1

Complexity
#

Time O(n), space O(1) (at most 26 letters).

Mistakes to Avoid
#

  • Return -1 when there is none.

Interview Explanation
#

I count characters, then scan left to right for the first one appearing once and return its index, or -1. Time O(n), space bounded by the alphabet.

Related

LeetCode 383: Ransom Note
·1 min
LeetCode Easy Hash-Table String Counting
LeetCode 383 note: every character’s demand in ransomNote must not exceed its supply in magazine; an empty Counter difference means yes
LeetCode 290: Word Pattern
·1 min
LeetCode Easy Hash-Table String
LeetCode 290 note: pattern characters and words must correspond one to one; use two dicts or compare set sizes
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains
LeetCode 409: Longest Palindrome
·2 mins
LeetCode Easy Hash-Table String Greedy
LeetCode 409 note: use an even number of each character on the two sides, plus one in the middle if any count is odd
LeetCode 242: Valid Anagram
·2 mins
LeetCode Easy Hash-Table String Sorting
LeetCode 242 note: two strings are anagrams exactly when their character counts match; compare Counters or sorted strings
LeetCode 205: Isomorphic Strings
·2 mins
LeetCode Easy Hash-Table String
LeetCode 205 note: characters must map one to one; it holds when the distinct characters and distinct pairs all have the same count