call(back)
Algorithms & Data StructureseasySign in to star problems

First Duplicate Character I

Find the first character that repeats: the one whose second occurrence comes earliest. firstDuplicate(str) returns that character, or null when nothing repeats.

firstDuplicate("abca")      // "a"
firstDuplicate("abcdefe")   // "e"
firstDuplicate("abcdef")    // null

Comparison is case-sensitive, spaces are characters, and an emoji counts as a single character.

Hints

Hint 1

One pass with a Set of the characters seen so far. The first character already in the set is the answer.

Hint 2

In JavaScript, for...of walks code points, so an emoji arrives whole. Indexing with str[i] walks UTF-16 units and splits it in two.

Asked at