Odd String Difference - Problem

You are given an array of equal-length strings words. Assume that the length of each string is n.

Each string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of 'a' is 0, 'b' is 1, and 'z' is 25.

For example, for the string "acb", the difference integer array is [2 - 0, 1 - 2] = [2, -1].

All the strings in words have the same difference integer array, except one. You should find that string.

Return the string in words that has different difference integer array.

Input & Output

Example 1 — Basic Case
$ Input: words = ["abc", "bcd", "acb"]
Output: "acb"
💡 Note: "abc" → [1,1] (b-a=1, c-b=1), "bcd" → [1,1] (c-b=1, d-c=1), "acb" → [2,-1] (c-a=2, b-c=-1). The string "acb" has a different pattern.
Example 2 — Different Position
$ Input: words = ["adc", "wzy", "abc"]
Output: "adc"
💡 Note: "adc" → [3,-1] (d-a=3, c-d=-1), "wzy" → [-3,1] (z-w=-3, y-z=1), "abc" → [1,1]. The string "adc" has a unique difference pattern.
Example 3 — Edge Case
$ Input: words = ["aaa", "bob", "ccc"]
Output: "bob"
💡 Note: "aaa" → [0,0] (a-a=0, a-a=0), "bob" → [13,-13] (o-b=13, b-o=-13), "ccc" → [0,0]. The string "bob" is the only one with non-zero differences.

Constraints

  • 3 ≤ words.length ≤ 100
  • n == words[i].length
  • 2 ≤ n ≤ 20
  • words[i] consists of lowercase English letters.

Visualization

Tap to expand
Odd String Difference INPUT words array: "abc" "bcd" "acb" Alphabet positions: a=0, b=1, c=2, d=3... All strings: length 3 [0] [1] [2] ALGORITHM STEPS 1 Compute Differences diff[i] = char[i+1] - char[i] "abc": [1-0, 2-1] = [1,1] "bcd": [2-1, 3-2] = [1,1] "acb": [2-0, 1-2] = [2,-1] 2 Three-Way Compare Compare first 3 diff arrays 3 Find Odd One If A==B, odd is different [1,1] == [1,1] ? YES [2,-1] != [1,1] --> ODD! 4 Return String Return word with odd diff FINAL RESULT Difference Arrays Comparison: "abc" --> [1, 1] OK "bcd" --> [1, 1] OK "acb" --> [2, -1] DIFF Output: "acb" The string "acb" has a different difference array Key Insight: Three-Way Comparison allows O(1) identification of the odd string. Compare first three difference arrays: If two match, the third is odd. If all three differ, compare with remaining strings to find the common pattern. Time: O(n*m) where n=words count, m=word length | Space: O(m) for difference array TutorialsPoint - Odd String Difference | Three-Way Comparison Approach
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~12 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen