LeetCode 884. Uncommon Words from Two Sentences

Description

https://leetcode.com/problems/uncommon-words-from-two-sentences/

We are given two sentences A and B.  (A sentence is a string of space separated words.  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.

Return a list of all uncommon words. 

You may return the list in any order.

Example 1:

Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]

Example 2:

Input: A = "apple apple", B = "banana"
Output: ["banana"]

Note:

  1. 0 <= A.length <= 200
  2. 0 <= B.length <= 200
  3. A and B both contain only spaces and lowercase letters.

Explanation

Count A words and B words separately and find out those words only occur either in A or B once.

Python Solution

class Solution:
    def uncommonFromSentences(self, A: str, B: str) -> List[str]:
        results = []
        
        a_counter = {}
        
        a_words = A.split()
        for word in a_words:
            a_counter[word] = a_counter.get(word, 0) + 1

        b_counter = {}
        b_words = B.split()        
        for word in b_words:            
            b_counter[word] = b_counter.get(word, 0) + 1
        
        for key, value in a_counter.items():
            if key not in b_counter and value == 1:
                results.append(key)
        
        for key, value in b_counter.items():
            if key not in a_counter and value == 1:
                results.append(key)        
        
        return results
  • Time Complexity: O(N).
  • Space Complexity: O(N).

Leave a Reply

Your email address will not be published.