|
| 1 | +# 2451. Odd String Difference |
| 2 | +You are given an array of equal-length strings `words`. Assume that the length of each string is `n`. |
| 3 | + |
| 4 | +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`. |
| 5 | + |
| 6 | +* For example, for the string `"acb"`, the difference integer array is `[2 - 0, 1 - 2] = [2, -1]`. |
| 7 | + |
| 8 | +All the strings in words have the same difference integer array, **except one**. You should find that string. |
| 9 | + |
| 10 | +Return *the string in* `words` *that has different **difference integer array***. |
| 11 | + |
| 12 | +#### Example 1: |
| 13 | +<pre> |
| 14 | +<strong>Input:</strong> words = ["adc","wzy","abc"] |
| 15 | +<strong>Output:</strong> "abc" |
| 16 | +<strong>Explanation:</strong> |
| 17 | +- The difference integer array of "adc" is [3 - 0, 2 - 3] = [3, -1]. |
| 18 | +- The difference integer array of "wzy" is [25 - 22, 24 - 25]= [3, -1]. |
| 19 | +- The difference integer array of "abc" is [1 - 0, 2 - 1] = [1, 1]. |
| 20 | +The odd array out is [1, 1], so we return the corresponding string, "abc". |
| 21 | +</pre> |
| 22 | + |
| 23 | +#### Example 2: |
| 24 | +<pre> |
| 25 | +<strong>Input:</strong> words = ["aaa","bob","ccc","ddd"] |
| 26 | +<strong>Output:</strong> "bob" |
| 27 | +<strong>Explanation:</strong> All the integer arrays are [0, 0] except for "bob", which corresponds to [13, -13]. |
| 28 | +</pre> |
| 29 | + |
| 30 | +#### Constraints: |
| 31 | +* `3 <= words.length <= 100` |
| 32 | +* `n == words[i].length` |
| 33 | +* `2 <= n <= 20` |
| 34 | +* `words[i]` consists of lowercase English letters. |
| 35 | + |
| 36 | +## Solutions (Python) |
| 37 | + |
| 38 | +### 1. Solution |
| 39 | +```Python |
| 40 | +class Solution: |
| 41 | + def oddString(self, words: List[str]) -> str: |
| 42 | + n = len(words[0]) |
| 43 | + difference = [] |
| 44 | + |
| 45 | + for i in range(len(words)): |
| 46 | + difference.append([]) |
| 47 | + for j in range(n - 1): |
| 48 | + difference[i].append(ord(words[i][j + 1]) - ord(words[i][j])) |
| 49 | + |
| 50 | + if i >= 2: |
| 51 | + prev = difference[i - 1] == difference[i - 2] |
| 52 | + curr = difference[i] == difference[i - 1] |
| 53 | + if prev and not curr: |
| 54 | + return words[i] |
| 55 | + elif not prev and curr: |
| 56 | + return words[i - 2] |
| 57 | + elif not prev and not curr: |
| 58 | + return words[i - 1] |
| 59 | +``` |
0 commit comments