LeetCode 884: Uncommon Words from Two Sentences Solution

Master LeetCode problem 884 (Uncommon Words from Two Sentences), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

884. Uncommon Words from Two Sentences

Problem Explanation

Explanation

  1. Split the input sentences s1 and s2 into words.
  2. Count the frequency of each word in both sentences.
  3. Identify the uncommon words based on the conditions given in the problem.
  4. Return the list of uncommon words.

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

Solution Code

import java.util.*;

class Solution {
    public String[] uncommonFromSentences(String s1, String s2) {
        Map<String, Integer> count = new HashMap<>();
        
        for (String word : (s1 + " " + s2).split(" ")) {
            count.put(word, count.getOrDefault(word, 0) + 1);
        }
        
        List<String> uncommon = new ArrayList<>();
        for (String word : count.keySet()) {
            if (count.get(word) == 1) {
                uncommon.add(word);
            }
        }
        
        return uncommon.toArray(new String[0]);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 884 (Uncommon Words from Two Sentences)?

This page provides optimized solutions for LeetCode problem 884 (Uncommon Words from Two Sentences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 884 (Uncommon Words from Two Sentences)?

The time complexity for LeetCode 884 (Uncommon Words from Two Sentences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 884 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 884 in Java, C++, or Python.

Back to LeetCode Solutions