DDSA Solutions

884. Uncommon Words from Two Sentences

Time: O(n)
Space: O(n)

Problem Overview

A word is uncommon if it appears exactly once across both sentences combined.

Intuition

A word is uncommon if it appears exactly once across both sentences combined. Concatenate both strings, count global frequencies, and return every word whose count equals one. Words appearing in both sentences twice still fail the uniqueness test.

Algorithm

  1. 1Split sentence A and B on spaces into word lists.
  2. 2Combine into one list (or count both in one pass).
  3. 3Build frequency map word -> count.
  4. 4Collect all keys where count == 1.
  5. 5Return as string array (order typically does not matter).

Example Walkthrough

Input: s = "s apple is apple", t = "s orange is orange"

  1. 1.Counts: s=1, apple=2, is=2, orange=2 — only "s" has count 1.

Output: ["s"]

Common Pitfalls

  • Count globally across both sentences — not per-sentence uniqueness.
  • Punctuation is absent in problem constraints; split on whitespace only.
  • Words with count 0 never appear; only count == 1 qualifies.
884.cs
C#
// Approach: Count word frequencies across both sentences combined; return words that appear exactly once.
// Time: O(n) Space: O(n)

public class Solution
{
    public string[] UncommonFromSentences(string s1, string s2)
    {
        var map = new Dictionary<string, int>();

        string[] words = (s1 + " " + s2).Split(" ");

        foreach (string word in words)
        {
            if (map.ContainsKey(word))
                map[word]++;
            else
                map[word] = 1;
        }

        var ans = new List<string>();
        foreach (KeyValuePair<string, int> item in map)
        {
            if (item.Value == 1)
                ans.Add(item.Key);
        }

        return ans.ToArray();
    }
}
Was this solution helpful?

Related Problems