We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Odd String Difference

Number: 2547

Difficulty: Easy

Paid? No

Companies: IBM, Visa


Problem Description

Given an array of equal-length strings, each string can be converted into a difference integer array. The difference for a given string is calculated by taking the difference between the positions (0-indexed) of consecutive characters in the alphabet. All strings share the same difference array except one; your task is to identify that one string.


Key Insights

  • Transform each word into its difference array by computing differences between consecutive characters.
  • Use the fact that all but one word will have an identical difference array.
  • Use hashing (or mapping) to count occurrences of each difference array representation.
  • Identify the unique difference array and return its corresponding string.

Space and Time Complexity

Time Complexity: O(m * n) where m is the number of words and n is the length of each word. Space Complexity: O(m * n) for storing the difference arrays.


Solution

The approach is to:

  1. Iterate over each word and compute its difference array.
  2. Convert the difference array into a hashable format (like a tuple or a string representation) so that it can be used as a key in a hash table.
  3. Count the frequencies of these difference array keys.
  4. Iterate through the words a second time and return the word whose difference array key has a frequency of one.

This method uses simple string and array operations, combined with dictionary/hash map lookups to efficiently determine the unique string.


Code Solutions

# Define the function to compute the odd string difference
def oddStringDifference(words):
    # Dictionary to store frequency of each difference array (as a tuple)
    diff_count = {}
    # Dictionary to map the difference array (tuple) to the word index
    diff_to_word = {}
    
    # Iterate over each word in the list
    for index, word in enumerate(words):
        # Compute the difference array for the current word
        diff = tuple(ord(word[i+1]) - ord(word[i]) for i in range(len(word) - 1))
        # Save the word index for this difference array (if not already saved)
        if diff not in diff_to_word:
            diff_to_word[diff] = index
        # Update frequency count of this difference array
        diff_count[diff] = diff_count.get(diff, 0) + 1
    
    # Find the difference array that occurred only once and return its corresponding word
    for diff, count in diff_count.items():
        if count == 1:
            return words[diff_to_word[diff]]
            
# Example usage:
words = ["adc", "wzy", "abc"]
print(oddStringDifference(words))  # Output: "abc"
← Back to All Questions