Find the first repeated word in string

Pattern: Hashing and frequency

medium

Read the words in order and return the first one that is already in a set of words seen so far.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given a sentence of lowercase words separated by single spaces. Return the first word that appears for the second time as you read from left to right. If no word repeats, return an empty string. For example, in "he had had quite enough of this nonsense" the answer is "had". In "a b c b a" the answer is "b", because the second "b" comes before the second "a".

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name firstRepeatedWord, the input format and the empty-string rule are this guide's own.

Think first

  • In "a b c b a", both "a" and "b" repeat. Which one counts as first under this problem's rule?
  • What do you need to remember about the words you have already read?
  • When can you stop reading?

Hints

    Brute force, and why it fails

    For each word, compare it with every word before it: O(w²) word comparisons for w words. A set makes each check about O(1), so the whole scan is linear in the length of the sentence.

    The key insight

    "Have I seen this before?" is a set membership question. Reading in order and stopping at the first "yes" gives exactly the earliest repeat.

    Dry run

    he0 
    had1 
    had2 
    quite3 
    enough4 
    seen{}

    The sentence is he had had quite enough. The words are taken in order, with an empty set of seen words.

    Step 1 of 4

    The plan

    seen = empty set
    for word in the words of sentence, in order:
        if word is in seen:
            return word
        add word to seen
    return ""
    

    Complexity

    Time
    O(L)
    Space
    O(L)

    L is the length of the sentence. Each word is hashed once, and the set holds the distinct words read so far.

    Edge cases

    • One word: nothing repeats, so the answer is an empty string.
    • Every word different: an empty string.
    • A word that repeats later than another word's repeat loses, as in "a b c b a", which gives "b".
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public String firstRepeatedWord(String sentence) {
            Set<String> seen = new HashSet<>();
            for (String word : sentence.split(" ")) {
                if (!seen.add(word)) {          // add() returns false if the word was already there
                    return word;
                }
            }
            return "";
        }
    }

    C++

    class Solution {
    public:
        string firstRepeatedWord(string sentence) {
            unordered_set<string> seen;
            stringstream words(sentence);
            string word;
            while (words >> word) {
                if (seen.count(word)) {
                    return word;
                }
                seen.insert(word);
            }
            return "";
        }
    };

    Python

    class Solution:
        def firstRepeatedWord(self, sentence):
            seen = set()
            for word in sentence.split(" "):
                if word in seen:
                    return word
                seen.add(word)
            return ""

    Common mistakes

    • Returning the word with the most repeats instead of the first one to repeat.
    • Returning the first word that has a repeat somewhere later ("a" in "a b c b a"), which is a different question.
    • Splitting on characters instead of on spaces.

    Similar problems