Suppose, we are provided an array that contains several strings that are of the same length. We have to find out if any two of the supplied strings differ by a single character at the same position. If this difference is present, we return true or else we return false.
So, if the input is like dict = ['pqrs', 'prqs', 'paqs'], then the output will be True. The output produced is True because the strings listed in the input all differ in index 1. So, if any two pairs are taken, there is a difference in the same position.
To solve this, we will follow these steps −
seens := a new set
for each word in dict, do
for each index i and character c in word, do
masked_word := word[from index 0 to i] + '.' + word[from index i+1 to end of string]
if masked_word is present in seens, then
return True
otherwise,
add(masked_word) to seens
return False
Example (Python)
Let us see the following implementation to get better understanding −
def solve(dict): seens = set() for word in dict: for i, c in enumerate(word): masked_word = word[:i] + '.' + word[i+1:] if masked_word in seens: return True else: seens.add(masked_word) return False print(solve(['pqrs', 'prqs', 'paqs']))
Input
['pqrs', 'prqs', 'paqs']
Output
True