File: odd-string-difference/solution.py

Date: 2026-06-06

Time: 18:26

Purpose

This file solves LeetCode 2451 — Odd String Difference. Given a list of equal-length strings, it finds the one string whose "difference array" (consecutive character ordinal differences) is unique among the group. Every other string shares the same difference array.

Key Components

stringWithDifferentDifference(words)

The main solver. Takes a list of equal-length lowercase strings and returns the one whose difference array is unique.

diff(w) (inner function)

Computes the difference array for a string as a tuple of integers. For a string of length n, it produces n-1 values where each value is ord(w[i+1]) - ord(w[i]). Returns a tuple so it's hashable and usable as a Counter key.

Patterns

Counter-based outlier detection: Rather than comparing pairs or using a majority-vote loop, the solution hashes every difference array and counts occurrences. The outlier is the one with count == 1. This is the idiomatic "find the unique element" pattern — the same approach you'd use for "single number" problems, generalized to tuples.

Tuple as hashable signature: The difference array is stored as a tuple (not a list) specifically so it can serve as a dictionary key in the Counter.

Dependencies

Flow

1. Compute diff(w) for every word, producing a list of tuples.

2. Feed all tuples into a Counter to get frequencies.

3. Iterate through (word, diff_tuple) pairs; return the first word whose diff tuple has a count of 1.

4. Fall through to return "" if no unique diff is found (unreachable given valid problem inputs).

Invariants

Error Handling

None. The function trusts its inputs match the problem constraints. The trailing return "" is a defensive fallback that can't trigger under valid inputs — it exists to satisfy the return-type contract.

Topics to Explore

Beliefs