Find the first word to appear a second time.
What to build
A program that asks one question for each word: have I seen this before?
Requirements
- Read a line of words.
- Go through them in order, and print the first word that has already appeared earlier in the line.
- Print
noneif no word repeats.
Input
One line of words separated by single spaces.
Output
One word.
Constraints
There are from 1 to 200 words.
Example
Input:
a b c b a
Output:
b
Why it works
b is the first word whose second appearance is reached, even though a appeared first. A Set answers has directly, so the program needs one pass through the line and no searching.
Examples
Example 1 · Input
a b c b a
Expected output
b
Example 2 · Input
x y z
Expected output
none
Hints
Hint 1
Keep a Set of the words you have already seen.
Hint 2
For each word, ask seen.has(word) before you add it.
Hint 3
Stop at the first word you have seen before.
Solution
Show one correct solution (try it yourself first)
const words = prompt().split(" ");
const seen = new Set();
let answer = "none";
for (const word of words) {
if (seen.has(word)) {
answer = word;
break;
}
seen.add(word);
}
console.log(answer);