KatInterview

920. Uncommon Words from Two Sentences

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find "uncommon words" from two sentences, s1 and s2. An uncommon word is defined as a word that appears exactly once in one of the sentences and not at all in the other.

Solution

Uncommon Words from Two Sentences in Python

import collections

class Solution:
    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
        # Combine the two sentences into a single list of words.
        # The `split()` method handles splitting the string by spaces.
        words = (s1 + " " + s2).split()
        
        # Use collections.Counter to efficiently count the frequency of each word.
        # This creates a dictionary-like object where keys are words and values are their counts.
        counts = collections.Counter(words)
        
        # Use a list comprehension to create a list of words
        # that appear exactly once in the combined list.
        return [word for word, count in counts.items() if count == 1]

Uncommon Words from Two Sentences in Java

class Solution {
    public String[] uncommonFromSentences(String s1, String s2) {
        // Use a HashMap to store the frequency of each word.
        Map<String, Integer> wordCounts = new HashMap<>();
        
        // Combine both sentences into a single string.
        String combined = s1 + " " + s2;
        
        // Split the combined string into words and count their frequencies.
        for (String word : combined.split(" ")) {
            wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
        }
        
        // Use a list to collect the uncommon words.
        List<String> uncommonWords = new ArrayList<>();
        
        // Iterate through the map's entries to find words that appear exactly once.
        for (Map.Entry<String, Integer> entry : wordCounts.entrySet()) {
            if (entry.getValue() == 1) {
                uncommonWords.add(entry.getKey());
            }
        }
        
        // Convert the list to a String array for the return type.
        return uncommonWords.toArray(new String[0]);
    }
}

Uncommon Words from Two Sentences in C++

class Solution {
public:
    vector<string> uncommonFromSentences(string s1, string s2) {
        // Use an unordered_map to store the frequency of each word.
        unordered_map<string, int> word_counts;
        
        // Combine both sentences into a single string stream for easy word extraction.
        stringstream ss(s1 + " " + s2);
        string word;
        
        // Extract words one by one and count their frequencies.
        while (ss >> word) {
            word_counts[word]++;
        }
        
        // Prepare a vector to store the result.
        vector<string> result;
        
        // Iterate through the map to find words that appear exactly once.
        for (auto const& [w, count] : word_counts) {
            if (count == 1) {
                result.push_back(w);
            }
        }
        
        return result;
    }
};

Uncommon Words from Two Sentences in TypeScript

function uncommonFromSentences(s1: string, s2: string): string[] {
    // Combine the two sentences into a single string and then split into an array of words.
    const words = (s1 + " " + s2).split(' ');

    // Use a Map to store the frequency of each word.
    const wordCounts = new Map<string, number>();

    // Iterate over the words to populate the frequency map.
    for (const word of words) {
        // Get the current count, default to 0 if not present, and increment it.
        wordCounts.set(word, (wordCounts.get(word) || 0) + 1);
    }

    // Initialize an array to store the result.
    const result: string[] = [];

    // Iterate through the map to find words that appear exactly once.
    wordCounts.forEach((count, word) => {
        if (count === 1) {
            result.push(word);
        }
    });

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.