The Only Difference

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Meta

Problem

A document editor lines up the original and edited version of a sentence so a reviewer can see what changed. Given the two versions as sentence_a and sentence_b, split each on whitespace and return the words present in exactly one version, with sentence_a's uniques listed before sentence_b's.

Two versions of the same line. Surface only what changed.

Example 1

Input:

sentence_a = "Facebook is an awesome place", sentence_b = "Facebook Is an AWESOME place"

Output:

["is","awesome","Is","AWESOME"]

Example 2

Input:

sentence_a = "the cat the dog", sentence_b = "the cat the fox"

Output:

["dog","fox"]

Worked solution and explanation

What this problem really is

This is an order-preserving symmetric difference dressed up as document diffing. Anyone can split the two strings and build a set from each; what separates candidates is seeing that the tempting one-liner, a_set ^ b_set, fails on two counts. A set has no order, but the contract wants A's uniques first, then B's, each in appearance order. And the moment you lowercase to 'normalize', you merge 'is' with 'Is' and 'awesome' with 'AWESOME', erasing the exact edits you were hired to surface.


Break down the requirements

Step 1: Split into lists, and mirror each into a set

Split each version on whitespace into a word list, and build a set from each list. Keep both: the lists preserve appearance order for the output, the sets give O(1) membership checks. A plain w in b_words list scan would also be correct, just O(n*m); the set is the cheap way to keep it linear.

Step 2: Filter each list by the opposite set

A word is a mismatch if it sits in one version's list but is absent from the other version. You test membership against the SET, but you walk the original LIST, so casing and order survive untouched. This is the case-sensitive part: 'is' and 'Is' are different keys, so neither cancels the other.

Step 3: A's words, then B's words, in order

Emit sentence_a's unique words first (in order of appearance), then sentence_b's unique words (in order of appearance). Concatenation of the two filtered lists gives exactly that.


The solution

Symmetric difference via set membership
def mismatched_words(sentence_a: str, sentence_b: str) -> list[str]:
    a_words = sentence_a.split()
    b_words = sentence_b.split()
    a_set = set(a_words)
    b_set = set(b_words)
    result = [w for w in a_words if w not in b_set]
    result += [w for w in b_words if w not in a_set]
    return result

Common follow-up questions