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

First Duplicate Character II

Return the position of the first repeat: the index of the character whose second occurrence comes earliest, or -1 when nothing repeats. firstDuplicateIndex(str).

firstDuplicateIndex("abca")     // 3   (the second "a")
firstDuplicateIndex("abba")     // 2   (the second "b")
firstDuplicateIndex("abcdef")   // -1

Comparison is case-sensitive, and spaces are characters. Inputs contain no emoji, so the index is the same in every language.

Hints

Hint 1

Walk the indices with a Set of the characters seen so far; the first index whose character is already in the set is the answer.

Asked at