Leetcode Problem 2451: Odd String Difference
Let’s define the “difference” between two strings (s1
, s2
) of the same length as the number of positions at which the corresponding characters are different. For example, the difference between "abc"
and "abx"
is 1
.
You are given an array of strings words
where each string has the same length. Return the string that differs from the rest of the strings in the array by an odd number of positions. It is guaranteed that there is exactly one such string in the array.
words
array and the length of each string within it?
2 <= len(words) <= 100
and 1 <= len(words[0]) <= 100
.words
, calculate the difference from the first string. Determine if the differences are even or odd.def find_odd_string(words):
def difference(s1, s2):
""" Calculate the number of differing positions between two strings of the same length """
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
# Calculate the difference of each string from the first one
differences = []
for i in range(1, len(words)):
diff = difference(words[0], words[i])
differences.append((diff, i))
# We assume that there is exactly one odd-indexed string
odd_string_index = -1
odd_counts = 0
even_counts = 0
for diff, idx in differences:
if diff % 2 == 1:
odd_counts += 1
odd_string_index = idx
else:
even_counts += 1
# Determine if the original string was the odd-one-out
if odd_counts == 1:
return words[odd_string_index]
else:
return words[0]
# Example Usage
words = ["abc", "abb", "acc"]
print(find_odd_string(words)) # Output: "abb" (as an example)
O(n)
, where n
is the length of the strings.O(m * n)
, where m
is the number of strings in the words
array and n
is the length of each string.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?