1042. First Repeated Word
A writing assistant highlights careless repetition. It reads sentence, a line of lowercase words separated by single spaces, from left to right and stops at the first moment it meets a word that it has already seen earlier in the line.
Return that word. In other words, among all words that occur at least twice, return the one whose second occurrence appears earliest in the sentence. If every word is unique, return null.
For example, in a line where the words 'sun' and 'moon' both repeat, the answer is whichever of them is repeated first when reading left to right, not whichever is first introduced.
Expected time is O(n) in the length of the sentence.
Example 1
- Input:
- sentence = "red green blue green red"
- Output:
- "green"
- Explanation:
green is met a second time (position 4) before red is met a second time (position 5), so green is returned.
Example 2
- Input:
- sentence = "one two three"
- Output:
- null
- Explanation:
No word occurs twice, so the answer is null.
Example 3
- Input:
- sentence = "echo echo"
- Output:
- "echo"
- Explanation:
The second word already appeared as the first, so echo is returned.
Constraints
1 ≤ sentence.length ≤ 105.
sentence consists of lowercase letters and single spaces; it has no leading or trailing space and no two consecutive spaces.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)