Find duplicate words

A very common interview challenge is to determine how often words appear in a given string or set of strings. Here’s a version of this: return a list of duplicate words in a sentence.

A very common interview challenge is to determine how often words appear in a given string or set of strings. Here’s a version of this: return a list of duplicate words in a sentence.

(Problem credits: AlgoDaily Day 97)

For example, given 'The dog is the best', returns ["the"].

Likewise, given 'Happy thanksgiving, I am so full', you would return an empty array. This is because there are no duplicates in the string.

My solution:

public static List<String> findDuplicates(String str){
     Set<String> set = new HashSet<>();
     List<String> res = new ArrayList<>();
     String[] words = str.split("\");
     for(int i = 0;i < words.length;i++)
     {
        if(set.contains(words[i].toLowercase())
          res.add(words[i]);
        else 
          set.add(words[i].toLowercase());
     }
     return res;
}

Time complexity: O(n) –> n = length of the string

Space complexity: O(n) –> String array words

Leave a comment