Find the first repeated word in a string

Easy

Problem

Given a sentence, return the first word that appears again later in the sentence (the earliest second occurrence), or report that no word repeats.

Example 1

Input:  "he had had quite enough of this nonsense"
Output: "had"

Also asked as: Find the first repeated word in string

Test cases

Case 1

Input:    "he had had quite enough of this nonsense"
Expected: "had"

Case 2

Input:    "a b c b a"
Expected: "b"

Case 3

Input:    "the cat the dog cat"
Expected: "the"

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Set of seen words

Time O(n)Space O(w)

Split on whitespace; the first word already in the set is the answer.

function firstRepeatedWord(s) {
const seen = new Set();
for (const w of s.toLowerCase().split(/\s+/)) {
if (seen.has(w)) return w;
seen.add(w);
}
return null;
}