Skip to content

884. Uncommon Words from Two Sentences

Solve in Leetcode


Description

Static Badge

A sentence is a string of single-space separated words where each word consists only of lowercase letters.

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.

Example 1

  • Input: s1 = "this apple is sweet", s2 = "this apple is sour"
  • Output: ["sweet","sour"]
  • Explanation: The word "sweet" appears only in s1, while the word "sour" appears only in s2.

Example 2

  • Input: s1 = "apple apple", s2 = "banana"
  • Output: ["banana"]

Constraints

  • 1 <= s1.length, s2.length <= 200
  • s1 and s2 consist of lowercase English letters and spaces.
  • s1 and s2 do not have leading or trailing spaces.
  • All the words in s1 and s2 are separated by a single space.

Solution: Duplicate Counting

First, we combine both sentences into a single string and split it into words. Then, we count the duplicate words.

Finally, we filter out the words that appear only once in the combined sentence.

  • Time Complexity: O(M+N),
    • where M is the total number of words in s1
    • and N is the total number of words in s2
  • Space Complexity: O(M+N)
    • where M is the total number of words in s1
    • and N is the total number of words in s2
function uncommonFromSentences(s1: string, s2: string): string[] {
    const duplicates: Record<string, number> = {};
    const combined = s1.split(" ").concat(s2.split(" "));

    for (let i = 0; i < combined.length; i++) {
        const word = combined[i];
        if (!duplicates[word]) {
            duplicates[word] = 0;
        }
        duplicates[word] += 1;
    }

    return Object.entries(duplicates)
        .filter(([key, value]) => value === 1)
        .map(([key]) => key);
};