Uncommon Words from Two Sentences

Below is the Python code to find all the uncommon words between two sentences, s1 and s2.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution:
    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
        # Split the sentences into words
        words_s1 = s1.split(" ")
        words_s2 = s2.split(" ")

        # Create dictionaries to count occurrences of words in s1 and s2
        count_s1 = {}
        count_s2 = {}

        # Count occurrences of words in s1
        for word in words_s1:
            if word in count_s1:
                count_s1[word] += 1
            else:
                count_s1[word] = 1

        # Count occurrences of words in s2
        for word in words_s2:
            if word in count_s2:
                count_s2[word] += 1
            else:
                count_s2[word] = 1

        # Find uncommon words
        uncommon_words = []

        # Check s1 words that are uncommon
        for word, count in count_s1.items():
            if count == 1 and word not in count_s2:
                uncommon_words.append(word)

        # Check s2 words that are uncommon
        for word, count in count_s2.items():
            if count == 1 and word not in count_s1:
                uncommon_words.append(word)

        return uncommon_words

Explanation:

  1. Split Sentences: We begin by splitting the sentences s1 and s2 into individual words.
  2. Count Words: Next, we use dictionaries to count the occurrences of each word in both sentences.
  3. Find Uncommon Words: We identify the words that appear exactly once in one sentence and not in the other, considering them as uncommon.
  4. Return Result: Finally, we return the list of uncommon words.

This code maintains a clear separation of steps and follows the problem constraints and requirements.