884. Uncommon Words from Two Sentences - Explanation

Problem Link

Description

A word is uncommon if it occurs exactly once in one sentence and never in the other. Given the sentences s1 and s2, return all uncommon words in any order. Each sentence contains lowercase English words separated by single spaces, with no leading or trailing spaces.

Example 1:

Input: s1 = "red blue"
s2 = "red green"

Output: ["blue","green"]

Explanation: The word "red" occurs in both sentences, so it is excluded. "blue" and "green" each occur once overall and are uncommon.

Example 2:

Input: s1 = "cat cat"
s2 = "dog"

Output: ["dog"]

Explanation: "cat" appears twice in the first sentence and is excluded. "dog" appears once in the second sentence and never in the first, so it is the only uncommon word.

Example 3:

Input: s1 = "a b"
s2 = "b a"

Output: []

Explanation: Both "a" and "b" appear in both sentences. Neither word is uncommon, so return an empty array.

Constraints:

  • 1 <= s1.length, s2.length <= 200
  • Both sentences contain only lowercase English letters and spaces.
  • Words are separated by one space, with no leading or trailing spaces.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.



Prerequisites

Before attempting this problem, you should be comfortable with:

  • Hash Maps - Using dictionaries or hash maps to count frequencies of elements
  • String Manipulation - Splitting strings into words and iterating through them

1. Hash Map - I

Intuition

A word is uncommon if it appears exactly once across both sentences. We can combine both sentences and count the frequency of each word. Any word with a count of 1 is uncommon.

Algorithm

  1. Split both sentences into words and combine them.
  2. Use a hash map to count the frequency of each word.
  3. Iterate through the hash map and collect all words with a count of 1.
  4. Return the list of uncommon words.
class Solution:
    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
        count = defaultdict(int)
        for w in s1.split(" ") + s2.split(" "):
            count[w] += 1

        res = []
        for w, cnt in count.items():
            if cnt == 1:
                res.append(w)
        return res

Time & Space Complexity

  • Time complexity: O(n+m)O(n + m)
  • Space complexity: O(n+m)O(n + m)

Where nn and mm are the lengths of the strings s1s1 and s2s2, respectively.


2. Hash Map - II

Intuition

This is a more concise version of the same approach. We use built-in functions like Counter (in Python) or stream operations (in Java) to reduce boilerplate while maintaining the same logic.

Algorithm

  1. Combine and split both sentences into words.
  2. Count word frequencies using a built-in counter or grouping function.
  3. Filter to keep only words with count equal to 1.
  4. Return the filtered words.
class Solution:
    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
        return [w for w, cnt in Counter(s1.split(" ") + s2.split(" ")).items() if cnt == 1]

Time & Space Complexity

  • Time complexity: O(n+m)O(n + m)
  • Space complexity: O(n+m)O(n + m)

Where nn and mm are the lengths of the strings s1s1 and s2s2, respectively.


Common Pitfalls

Misunderstanding "Uncommon" Definition

A word is uncommon if it appears exactly once across both sentences combined, not once per sentence. Some mistakenly check if a word appears in one sentence but not the other, which is incorrect. A word appearing twice in the same sentence is also not uncommon.

Incorrect String Splitting

When splitting sentences into words, be careful with edge cases like multiple spaces or empty strings. The problem guarantees single spaces between words, but forgetting to handle the concatenation properly (e.g., not adding a space between s1 and s2) can cause words at the boundary to merge incorrectly.