Replace two Substrings (of a String) with Each Other

Replacing two substrings with each other requires careful handling of overlapping matches. Python provides several approaches to solve this problem efficiently using string methods and regular expressions.

Problem Understanding

Given a string S and two substrings A and B, we need to replace every occurrence of A with B and every occurrence of B with A. When both substrings are found at the same position, we prioritize the leftmost match.

Example

S = "aab"
A = "aa" 
B = "bb"
# Expected output: "bbb"
print(f"Input: S='{S}', A='{A}', B='{B}'")
Input: S='aab', A='aa', B='bb'

Using String Iteration Method

This approach scans the string from left to right, finding the leftmost matching substring at each step ?

def replace_substrings(s, a, b):
    result = []
    i = 0
    
    while i < len(s):
        # Check if substring A matches at current position
        if i + len(a) <= len(s) and s[i:i+len(a)] == a:
            result.append(b)
            i += len(a)
        # Check if substring B matches at current position  
        elif i + len(b) <= len(s) and s[i:i+len(b)] == b:
            result.append(a)
            i += len(b)
        # No match, add current character
        else:
            result.append(s[i])
            i += 1
            
    return ''.join(result)

# Test with examples
s1 = "aab"
result1 = replace_substrings(s1, "aa", "bb")
print(f"'{s1}' ? '{result1}'")

s2 = "aabbaabb" 
result2 = replace_substrings(s2, "aa", "bb")
print(f"'{s2}' ? '{result2}'")
'aab' ? 'bbb'
'aabbaabb' ? 'bbaabbaa'

Using Regular Expressions

For more complex patterns, regular expressions provide a powerful solution ?

import re

def replace_with_regex(s, a, b):
    # Create pattern that matches either A or B
    pattern = f'({re.escape(a)}|{re.escape(b)})'
    
    def replacer(match):
        if match.group(0) == a:
            return b
        else:
            return a
    
    return re.sub(pattern, replacer, s)

# Test the regex approach
s1 = "aab"
result1 = replace_with_regex(s1, "aa", "bb")
print(f"'{s1}' ? '{result1}'")

s2 = "aabbaabb"
result2 = replace_with_regex(s2, "aa", "bb") 
print(f"'{s2}' ? '{result2}'")
'aab' ? 'bbb'
'aabbaabb' ? 'bbaabbaa'

Using Temporary Placeholder Method

This approach uses a temporary placeholder to avoid conflicts during replacement ?

def replace_with_placeholder(s, a, b):
    # Use a unique placeholder that won't appear in the string
    placeholder = "###TEMP###"
    
    # Replace A with placeholder, then B with A, then placeholder with B
    result = s.replace(a, placeholder)
    result = result.replace(b, a)
    result = result.replace(placeholder, b)
    
    return result

# Test the placeholder approach
s1 = "aabbaabb"
result1 = replace_with_placeholder(s1, "aa", "bb")
print(f"'{s1}' ? '{result1}'")

# Test with different substrings
s2 = "hello world hello"
result2 = replace_with_placeholder(s2, "hello", "hi")
print(f"'{s2}' ? '{result2}'")
'aabbaabb' ? 'bbaabbaa'
'hello world hello' ? 'hi world hi'

Comparison

Method Time Complexity Best For
String Iteration O(n) Precise control, overlapping patterns
Regular Expressions O(n) Complex patterns, multiple replacements
Placeholder O(n) Simple cases, non-overlapping patterns

Conclusion

Use string iteration for precise control over overlapping matches. Regular expressions work well for complex patterns, while the placeholder method is simple but may not handle all edge cases correctly.

Updated on: 2026-03-27T13:12:37+05:30

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements