#2451

Odd String Difference

Easy
ArrayHash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a hash map to count the occurrences of each difference array. This allows us to find the odd string in a single pass through the list, making it much more efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hash map to store the frequency of each difference array.
  2. 2Step 2: For each string, calculate its difference array and update the hash map.
  3. 3Step 3: Iterate through the strings again to find the one with a unique difference array in the hash map.
  4. 4Step 4: Return the corresponding string.
solution.py14 lines
1# Full working Python code
2
3def oddString(words):
4    def get_diff_array(s):
5        return [ord(s[i+1]) - ord(s[i]) for i in range(len(s)-1)]
6
7    diff_count = {}
8    for word in words:
9        diff = tuple(get_diff_array(word))
10        diff_count[diff] = diff_count.get(diff, 0) + 1
11
12    for word in words:
13        if diff_count[tuple(get_diff_array(word))] == 1:
14            return word

Complexity note: This complexity is due to a single pass through the words to build the hash map (O(n)) and another pass to find the unique string (O(n)).

  • 1Understanding how to calculate the difference array is crucial.
  • 2Using a hash map can significantly reduce time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.