Talentd
FleetCode
Make and follow sheets.Sign in

Uncommon Words from Two Sentences solution and explanation

EasyCountingHash TableString5 min read75.8% acceptanceUpdated 9 Apr 2026
Uncommon Words from Two Sentences - Leetcode 884 - PythonNeetCodeIO · 5:30 · 6K viewsWatch on YouTube
9 more videos on this problem
  1. Uncommon Words from Two Sentences - Leetcode 884 - PythonNeetCodeIO · 5:30 · 6K views
  2. LeetCode in Python 884. Uncommon Words from Two Sentences (Easy)|String - Michelle小梦想家Michelle小梦想家 · 29:02 · 551 views
  3. How to Solve "884 Uncommon Words from Two Sentences" on LeetCode? - JavascriptBecoming A Better Dev (with David) · 7:35 · 464 views
  4. Leetcode | 884. Uncommon Words from Two Sentences | Easy | Java SolutionDeveloper Docs · 8:02 · 371 views
  5. UNCOMMON WORDS FROM TWO SENTENCES| LEETCODE 884 | PYTHON SOLUTIONCracking FAANG · 4:10 · 346 views
  6. 884. Uncommon Words from Two Sentences with python | Leetcode with Python #leetcode #youtubeArsalan Ahmed · 6:17 · 254 views
  7. Leetcode solving: 884. Uncommon Words from Two SentencesMath Geeks · 1:57 · 180 views
  8. 💡 LeetCode 884 | 📝 Uncommon Words from Two Sentences | Java Solution 🚀Recurso · 12:25 · 141 views
  9. Uncommon Words from Two Sentences - Leetcode 884 - JavaCode With K5KC · 6:00 · 88 views
  10. Uncommon Words from Two Sentences | Leetcode 884 | Java | Developer CoderDeveloper Coder · 8:09 · 74 views

The problem

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.

Approach overview

Problem Overview: You receive two space-separated sentences s1 and s2. A word is considered uncommon if it appears exactly once in one sentence and does not appear in the other sentence. The task is to return all such uncommon words.

This problem is mostly about counting occurrences of words across two strings. Once you can quickly check how often each word appears, filtering uncommon words becomes straightforward. The typical solution uses a hash table to store frequencies and relies on simple string parsing.

Approach 1: Using Frequency Count (O(n) time, O(n) space)

Split both sentences into word arrays and count the frequency of every word using a hash map. Insert words from both sentences into the same map, incrementing the count each time a word appears. After processing all tokens, iterate through the map and collect the words whose frequency is exactly 1. These are the words that appear once across both sentences and therefore satisfy the definition of uncommon.

The key insight: if a word appears once in one sentence and zero times in the other, the combined frequency is 1. If it appears in both sentences or multiple times in one sentence, its count will be greater than 1 and should be ignored. This approach uses constant-time hash lookups and is the most direct implementation of frequency counting.

This solution runs in O(n) time where n is the total number of words across both sentences. Space complexity is O(n) for storing the frequency map.

Approach 2: Merging and Identifying Uniques (O(n) time, O(n) space)

Another approach keeps counts for each sentence separately, then merges the results. First, split both sentences and build two frequency maps: one for s1 and one for s2. Next, iterate through the first map and select words with frequency 1 that do not exist in the second map. Repeat the same logic for the second map against the first.

This approach explicitly enforces the problem definition: the word must appear once in one sentence and zero times in the other. Although slightly more verbose, it improves clarity because each condition is checked directly rather than inferred from a combined count.

Time complexity remains O(n) since each word is processed a constant number of times. Space complexity is O(n) due to the two hash maps storing word frequencies.

Recommended for interviews: The combined frequency map approach is what interviewers usually expect. It demonstrates comfort with hash-based counting and leads to clean O(n) time complexity. The separate-map merging approach is still valid and can help explain the definition of "uncommon" more explicitly, but the single map solution is shorter and easier to implement during interviews.

Approach 1: Using Frequency Count

In this approach, we compute the frequency of each word in both sentences. We then check for words that appear exactly once in one sentence and do not appear in the other sentence. This can be efficiently achieved by using hash maps (or dictionaries) to store these frequencies.

def uncommonFromSentences(s1, s2):
    from collections import Counter
    count1 = Counter(s1.split())
    count2 = Counter(s2.split())
    result = []
    
    for word in count1:
        if count1[word] == 1 and word not in count2:
            result.append(word)
    for word in count2:
        if count2[word] == 1 and word not in count1:
            result.append(word)
    
    return result
function uncommonFromSentences(s1, s2) {
    const countWords = (sentence) => {
        const words = sentence.split(' ');
        const map = {};
        for (const word of words) {
            map[word] = (map[word] || 0) + 1;
        }
        return map;
    };
    
    const count1 = countWords(s1);
    const count2 = countWords(s2);
    const result = [];

    for (const word in count1) {
        if (count1[word] === 1 && !count2[word]) {
            result.push(word);
        }
    }
    for (const word in count2) {
        if (count2[word] === 1 && !count1[word]) {
            result.push(word);
        }
    }

    return result;
}

First, we split each of the sentences into words and count the occurrences using the Counter class from the collections module. We then iterate over these counts and check for words that meet our uncommon criteria. These words are collected in a result list.

Complexity

Time Complexity: O(n + m), where n and m are the lengths of s1 and s2 respectively, due to splitting and counting.

Space Complexity: O(n + m) due to storage for hash maps.

Try this approach in the editor

Approach 2: Merging and Identifying Uniques

This approach involves merging both sentences into one list of words, along with a source identifier to track which sentence they came from. By counting occurrences in this merged list, we can determine uncommon words.

import java.util.*;

public class Solution {
    public List<String> uncommonFromSentences(String s1, String s2) {
        Map<String, Integer> count = new HashMap<>();
        String[] words = (s1 + " " + s2).split(" ");
        
        for (String word : words) {
            count.put(word, count.getOrDefault(word, 0) + 1);
        }

        List<String> result = new ArrayList<>();
        for (String word : count.keySet()) {
            if (count.get(word) == 1) {
                result.add(word);
            }
        }

        return result;
    }
}
#include <unordered_map>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

vector<string> uncommonFromSentences(string s1, string s2) {
    unordered_map<string, int> wordCount;
    istringstream stream(s1 + " " + s2);
    string word;
    while (stream >> word) {
        wordCount[word]++;
    }
    vector<string> result;
    for (auto &entry : wordCount) {
        if (entry.second == 1) {
            result.push_back(entry.first);
        }
    }
    return result;
}

We create a map to hold word counts after merging both sentences, using split to create a word list. Words occurring once in total are collected into a result list.

Complexity

Time Complexity: O(n + m) due to merging and counting operations.

Space Complexity: O(n + m) for storage in the map.

Try this approach in the editor

Approach 3: Hash Table

According to the problem description, as long as a word appears once, it meets the requirements of the problem. Therefore, we use a hash table cnt to record all words and their occurrence counts.

Then we traverse the hash table, and take out all strings that appear only once.

The time complexity is O(m + n), and the space complexity is O(m + n). Here, m and n are the lengths of strings s1 and s2, respectively.

function uncommonFromSentences(s1: string, s2: string): string[] {
    const cnt: Map<string, number> = new Map();
    for (const s of [...s1.split(' '), ...s2.split(' ')]) {
        cnt.set(s, (cnt.get(s) || 0) + 1);
    }
    const ans: Array<string> = [];
    for (const [s, v] of cnt.entries()) {
        if (v == 1) {
            ans.push(s);
        }
    }
    return ans;
}
func uncommonFromSentences(s1 string, s2 string) (ans []string) {
	cnt := map[string]int{}
	for _, s := range strings.Split(s1, " ") {
		cnt[s]++
	}
	for _, s := range strings.Split(s2, " ") {
		cnt[s]++
	}
	for s, v := range cnt {
		if v == 1 {
			ans = append(ans, s)
		}
	}
	return
}
use std::collections::HashMap;

impl Solution {
    pub fn uncommon_from_sentences(s1: String, s2: String) -> Vec<String> {
        let mut map = HashMap::new();
        for s in s1.split(' ') {
            map.insert(s, !map.contains_key(s));
        }
        for s in s2.split(' ') {
            map.insert(s, !map.contains_key(s));
        }
        let mut res = Vec::new();
        for (k, v) in map {
            if v {
                res.push(String::from(k));
            }
        }
        res
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Using Frequency Count

Time Complexity: O(n + m), where n and m are the lengths of s1 and s2 respectively, due to splitting and counting.

Space Complexity: O(n + m) due to storage for hash maps.

Merging and Identifying Uniques

Time Complexity: O(n + m) due to merging and counting operations.

Space Complexity: O(n + m) for storage in the map.

Hash Table–

Complexity analysis

ApproachTimeSpaceWhen to Use
Frequency Count with Single Hash MapO(n)O(n)Best general solution. Minimal code and efficient hash lookups.
Separate Maps and Merge UniquesO(n)O(n)Useful when you want to explicitly track counts per sentence.

Frequently asked questions

Is Uncommon Words from Two Sentences easy or hard?

Uncommon Words from Two Sentences is categorized as an Easy problem. The challenge mainly tests familiarity with string splitting and hash map frequency counting rather than advanced algorithms.

Uncommon Words from Two Sentences Python/Java solution

In Python, you typically use a dictionary or collections.Counter to track word frequencies. In Java, a HashMap<String, Integer> performs the same role. Both implementations split the sentences into tokens, update counts, and return words whose frequency equals 1.

How to solve Uncommon Words from Two Sentences in O(n)?

Split both sentences into words and insert them into a hash map that tracks frequency. After counting all occurrences, iterate through the map and collect words with frequency equal to 1. Because each word is processed a constant number of times, the total complexity stays O(n).

What is the best approach for Uncommon Words from Two Sentences?

The most efficient approach uses a hash table to count word frequencies across both sentences. Split the sentences into words, store counts in a map, then return the words with frequency exactly 1. This runs in O(n) time with O(n) space and is the standard interview solution.

Is Uncommon Words from Two Sentences asked at Google/Amazon/Meta?

Problems involving word frequency counting and hash maps appear frequently in interviews at companies like Amazon, Google, and Meta. While this exact problem may not always appear, the underlying pattern of counting occurrences in strings is common in coding interviews.

What data structure is used in Uncommon Words from Two Sentences?

The primary data structure is a hash table (hash map) that stores each word as a key and its frequency as the value. This allows constant-time updates and lookups while counting occurrences across both sentences.

What is the time complexity of Uncommon Words from Two Sentences?

The optimal solution runs in O(n) time, where n is the total number of words across both sentences. Each word is processed once during splitting and counting, and hash map lookups take constant time on average.

Comments

Now write it yourselfClose this page and solve Uncommon Words from Two Sentences in the editor, without looking.
Practise Uncommon Words from Two Sentences