Uncommon Words from Two Sentences

A sentence is a string of single-space separated words of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences and does not appear in the other. Given two sentences `s1` and `s2`, return a list of all the uncommon words in any order.

30:00

Uncommon Words from Two Sentences
easy
Free written solution
Topics
Companies

A sentence is a string of single-space separated words of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences and does not appear in the other. Given two sentences s1 and s2, return a list of all the uncommon words in any order.

Example 1:
Input: {"s1":"this apple is sweet","s2":"this apple is sour"}
Output: ["sweet","sour"]
Constraints:
  • 1≤s1.length,s2.length≤2001 \leq \text{s1.length}, \text{s2.length} \leq 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.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s1":"this apple is sweet","s2":"this apple is sour"}

Uncommon means once in one sentence and never in the other, which is the same as appearing exactly once across both. So count every word of s1 and s2 together.

both sentences, counted as one stream

s1

this
apple
is
sweet

s2

this
apple
is
sour

count map (word: total over s1 and s2)

empty

count 1: uncommon

count 2+: appears more than once overall

result

filled after counting

Variables
VariableValue
distinct words0
res[]
DepthFunction Call
Stack empty
0/14