↓Skip to main content
  1. LeetCode/

LeetCode 884: Uncommon Words from Two Sentences

·1 min· ·
LeetCode Easy Hash-Table String Counting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-21

  • Submissions: Wrong Answer → Accepted ×2

Approach
#

“Exactly once in one sentence and absent from the other” equals “exactly once across both”. Join, split(), count, and keep words with count 1 (Hash Table Template 1).

My Attempts
#

Attempt 1 forgot to split and looped over the string, counting characters: "b", "b" returned the separating space [" "].

Solution
#

class Solution:
    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
        cnt = Counter((s1 + " " + s2).split())
        return [w for w, c in cnt.items() if c == 1]

Complexity
#

Time O(n + m), space O(n + m).

Mistakes to Avoid
#

  • split() into words first; iterating a string yields characters.

Interview Explanation
#

I join both sentences, split into words, count, and return the words seen exactly once. Time O(n + m).

Related

LeetCode 819: Most Common Word
·2 mins
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 note: replace punctuation with spaces, lowercase, split, count, and pick the most frequent word not banned
LeetCode 383: Ransom Note
·1 min
LeetCode Easy Hash-Table String Counting
LeetCode 383 note: every character’s demand in ransomNote must not exceed its supply in magazine; an empty Counter difference means yes
LeetCode 387: First Unique Character in a String
·1 min
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 note: count first, then scan left to right for the first character with count 1
LeetCode 859: Buddy Strings
·2 mins
LeetCode Easy Hash-Table String
LeetCode 859 note: lengths must match; identical strings need a repeated character; otherwise exactly two positions differ and cross-match
LeetCode 771: Jewels and Stones
·1 min
LeetCode Easy Hash-Table String
LeetCode 771 note: put jewels in a set and count how many stones are in it
LeetCode 748: Shortest Completing Word
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 748 note: count the plate’s letters in lowercase, then find the shortest word covering every count, taking the earliest on ties