Program to find out if the strings supplied differ by a character in the same position in Python

Suppose, we are provided an array that contains several strings 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, otherwise we return False.

So, if the input is like words = ['pqrs', 'prqs', 'paqs'], then the output will be True. The output is True because all strings differ at index 1 ('q', 'r', 'a'), so any two pairs have a difference in the same position.

Algorithm Steps

To solve this, we will follow these steps −

  • Create a set called seen to store masked patterns

  • For each word in the input list, do

    • For each index i and character c in word, do

      • Create masked_word by replacing character at position i with '.'

      • If masked_word is already in seen, return True

      • Otherwise, add masked_word to seen

  • Return False if no matches found

Example

Let us see the following implementation to get better understanding −

def solve(words):
    seen = set()
    for word in words:
        for i, c in enumerate(word):
            masked_word = word[:i] + '.' + word[i+1:]
            if masked_word in seen:
                return True
            else:
                seen.add(masked_word)
    return False

# Test the function
words = ['pqrs', 'prqs', 'paqs']
result = solve(words)
print(f"Input: {words}")
print(f"Output: {result}")
Input: ['pqrs', 'prqs', 'paqs']
Output: True

How It Works

The algorithm creates masked patterns by replacing each character with a dot ('.'). For the input ['pqrs', 'prqs', 'paqs']

  • For 'pqrs': creates patterns '.qrs', 'p.rs', 'pq.s', 'pqr.'

  • For 'prqs': creates patterns '.rqs', 'p.qs', 'pr.s', 'prq.'

  • When processing 'prqs', the pattern 'p.rs' (from 'pqrs') matches 'p.qs', so it returns True

Additional Example

Let's test with strings that don't have differences in the same position −

def solve(words):
    seen = set()
    for word in words:
        for i, c in enumerate(word):
            masked_word = word[:i] + '.' + word[i+1:]
            if masked_word in seen:
                return True
            else:
                seen.add(masked_word)
    return False

# Test with no common position differences
words = ['abc', 'def', 'ghi']
result = solve(words)
print(f"Input: {words}")
print(f"Output: {result}")
Output: False

Conclusion

This algorithm efficiently detects if any two strings differ by exactly one character at the same position using pattern matching with masks. The time complexity is O(n*m) where n is the number of words and m is the word length.

Updated on: 2026-03-25T20:37:07+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements