Program to check whether one string swap can make strings equal or not using Python

Given two strings of equal length, we need to determine if we can make them identical by performing at most one swap operation on exactly one of the strings. A swap operation exchanges two characters at any positions within a string.

Problem Analysis

For two strings to become equal with at most one swap, they must satisfy these conditions:

  • If strings are already identical (0 differences) − return True

  • If strings have exactly 2 differences − check if swapping makes them equal

  • If strings have more than 2 differences − return False

  • Both strings must contain the same set of unique characters

Algorithm Steps

Here's our approach to solve this problem:

  1. Count the number of positions where characters differ

  2. Track unique characters in both strings using sets

  3. Return True if differences are 0 or 2, and both strings have same character sets

Example

Let's implement the solution with a complete example:

def can_make_equal_with_swap(s, t):
    max_diffs = 2
    diffs = 0
    chars_s = set()
    chars_t = set()
    
    for i in range(len(s)):
        if s[i] != t[i]:
            diffs += 1
        
        chars_s.add(s[i])
        chars_t.add(t[i])
        
        if diffs > max_diffs:
            return False
    
    return (diffs == 0 or diffs == 2) and chars_s == chars_t

# Test with the given example
s = "hello"
t = "hlelo"
result = can_make_equal_with_swap(s, t)
print(f"Can '{s}' and '{t}' be made equal with one swap? {result}")

# Let's trace the differences
print(f"\nTracing differences:")
for i, (char_s, char_t) in enumerate(zip(s, t)):
    if char_s != char_t:
        print(f"Position {i}: '{char_s}' != '{char_t}'")
Can 'hello' and 'hlelo' be made equal with one swap? True

Tracing differences:
Position 1: 'e' != 'l'
Position 2: 'l' != 'e'

Testing Different Cases

Let's test various scenarios to understand the algorithm better:

def can_make_equal_with_swap(s, t):
    max_diffs = 2
    diffs = 0
    chars_s = set()
    chars_t = set()
    
    for i in range(len(s)):
        if s[i] != t[i]:
            diffs += 1
        
        chars_s.add(s[i])
        chars_t.add(t[i])
        
        if diffs > max_diffs:
            return False
    
    return (diffs == 0 or diffs == 2) and chars_s == chars_t

# Test cases
test_cases = [
    ("hello", "hello"),  # Already equal
    ("hello", "hlelo"),  # Can swap e and l
    ("abc", "bac"),      # Can swap a and b
    ("abc", "def"),      # Different characters
    ("abcd", "abdc"),    # Can swap c and d
    ("abc", "acb")       # More than 2 differences
]

for s, t in test_cases:
    result = can_make_equal_with_swap(s, t)
    print(f"'{s}' and '{t}': {result}")
'hello' and 'hello': True
'hello' and 'hlelo': True
'abc' and 'bac': True
'abc' and 'def': False
'abcd' and 'abdc': True
'abc' and 'acb': False

How It Works

The algorithm works by checking these key conditions:

Condition Meaning Result
0 differences Strings already equal True
2 differences Can potentially swap to make equal Check character sets
>2 differences Too many differences for one swap False
Same character sets Both strings contain same unique chars Required for True

Conclusion

This solution efficiently determines if two strings can be made equal with at most one swap operation. The key insight is that valid cases have either 0 or exactly 2 character differences, and both strings must contain the same set of unique characters.

Updated on: 2026-03-25T20:51:26+05:30

549 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements