KatInterview

Find Unique Words Across Two Text Blocks

StringsModel answer
EasyModel answerStringsstringsarraysset-operations

Last updated

Identify words that appear in either of two given text strings, but not in both, using symmetric set difference.

Write a function unique_words(text1: str, text2: str) -> list[str] that processes two text strings and identifies all words that occur in exactly one of the strings. In set theory, this corresponds to finding the symmetric difference between the word sets of both inputs.

Rules & Expectations

  1. Duplicates: Multiple occurrences of a word within the same string should only yield a single instance of that word in the final output.
  2. Exclusions: Any word present in both text1 and text2 must be excluded from the final output.
  3. Ordering: The output list can return words in any order.
  4. Tokenization & Case: Unless specified otherwise during clarification, assume words are separated by whitespace and comparison should be treated as case-insensitive (normalize to lowercase).

Example 1

text1 = "apple banana apple"
text2 = "banana cherry"

# Output: ["apple", "cherry"] (or ["cherry", "apple"])
# Explanation: "banana" is in both strings. "apple" is only in text1, and "cherry" is only in text2.

Example 2

text1 = "Hello World"
text2 = "hello world"

# Output: []
# Explanation: Case-insensitive normalization makes both sets identical ({"hello", "world"}), so no unique words exist.