First Unique Character in a String

Given a string s, find the first character that appears exactly once in it and return its index. If every character repeats, return -1.

30:00

First Unique Character in a String
easy
Free written solution
Topics
Companies

Given a string s, find the first character that appears exactly once in it and return its index. If every character repeats, return -1.

Example 1:
Input: {"s":"leetcode"}
Output: 0
Constraints:
  • 1≤s.length≤1051 \leq s.\text{length} \leq 10^5

  • s consists of only lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"leetcode"}

Two passes over "leetcode": first count every letter, then find the first one whose count is 1.

pass 1 · count letters
pass 2 · find first count == 1

s (8 chars)

▼

l

0

×0

▼

e

1

×0

▼

e

2

×0

▼

t

3

×0

▼

c

4

×0

▼

o

5

×0

▼

d

6

×0

▼

e

7

×0

tally board (count)

l

0

e

0

t

0

c

0

o

0

d

0

Variables
VariableValue
sleetcode
DepthFunction Call
Stack empty
0/12