First Letter to Appear Twice

Given a string `s` of lowercase English letters, return the first letter to appear twice. Letter `a` appears twice before letter `b` if the second occurrence of `a` comes before the second occurrence of `b`. The string is guaranteed to contain at least one letter that appears twice.

30:00

First Letter to Appear Twice
easy
Free written solution
Topics
Companies

Given a string s of lowercase English letters, return the first letter to appear twice. Letter a appears twice before letter b if the second occurrence of a comes before the second occurrence of b. The string is guaranteed to contain at least one letter that appears twice.

Example 1:
Input: {"s":"abccbaacz"}
Output: c
Constraints:
  • 2≤s.length≤1002 \leq s.\text{length} \leq 100

  • s consists of lowercase English letters.

  • s has at least one repeated letter.

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

Run code to see results.

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

s, read left to right: current letter

a

0

b

1

c

2

c

3

b

4

a

5

a

6

c

7

z

8

seen set: lit slot = letter already met (small number = index of its first copy)

a

·

b

·

c

·

d

·

e

·

f

·

g

·

h

·

i

·

j

·

k

·

l

·

m

·

n

·

o

·

p

·

q

·

r

·

s

·

t

·

u

·

v

·

w

·

x

·

y

·

z

·

Start with an empty set of seen letters: 26 empty slots, one per letter.

Variables
VariableValue
seen0
DepthFunction Call
Stack empty
0/8