Program to find minimum number of operations required to make one string substring of other in Python

Suppose we have two strings s and t, we have to find the minimum number of operations required to make t a substring of s. In each operation, we can choose any position in s and change the character at that position to any other character.

For example, if s = "abbpqr" and t = "bbxy", then the output will be 2. We can take the substring "bbpq" from s and change 'p' to 'x' and 'q' to 'y' to make "bbxy" a substring.

Approach

The strategy is to check all possible substrings of s that have the same length as t, and count how many characters need to be changed for each substring ?

  • k := length of t, n := length of s
  • ans := initialize to a large number
  • For each position i from 0 to n - k:
    • Extract substring ss of s from index i to i+k-1
    • Count mismatched characters between ss and t
    • Update ans with the minimum count
  • Return ans

Implementation

class Solution:
    def solve(self, s, t):
        k, n = len(t), len(s)
        ans = 10**10
        
        for i in range(n - k + 1):
            ss = s[i:i+k]
            # Count mismatched characters
            mismatches = sum(ss[j] != t[j] for j in range(k))
            ans = min(ans, mismatches)
        
        return ans

# Test the solution
ob = Solution()
result = ob.solve("abbpqr", "bbxy")
print(f"Minimum operations required: {result}")
Minimum operations required: 2

How It Works

Let's trace through the example step by step ?

def detailed_solve(s, t):
    k, n = len(t), len(s)
    print(f"String s: '{s}' (length {n})")
    print(f"String t: '{t}' (length {k})")
    print()
    
    min_operations = 10**10
    
    for i in range(n - k + 1):
        substring = s[i:i+k]
        mismatches = sum(substring[j] != t[j] for j in range(k))
        
        print(f"Position {i}: '{substring}' vs '{t}' -> {mismatches} mismatches")
        min_operations = min(min_operations, mismatches)
    
    return min_operations

result = detailed_solve("abbpqr", "bbxy")
print(f"\nMinimum operations needed: {result}")
String s: 'abbpqr' (length 6)
String t: 'bbxy' (length 4)

Position 0: 'abbp' vs 'bbxy' -> 3 mismatches
Position 1: 'bbpq' vs 'bbxy' -> 2 mismatches
Position 2: 'bpqr' vs 'bbxy' -> 4 mismatches

Minimum operations needed: 2

Alternative Implementation

Here's a more concise version without using a class ?

def min_operations_to_substring(s, t):
    """
    Find minimum operations to make t a substring of s.
    
    Args:
        s (str): Source string
        t (str): Target substring
    
    Returns:
        int: Minimum number of character changes needed
    """
    if len(t) > len(s):
        return float('inf')  # Impossible case
    
    min_changes = float('inf')
    
    # Check all possible positions where t can fit in s
    for i in range(len(s) - len(t) + 1):
        changes = sum(s[i + j] != t[j] for j in range(len(t)))
        min_changes = min(min_changes, changes)
    
    return min_changes

# Test cases
test_cases = [
    ("abbpqr", "bbxy"),
    ("hello", "lo"),
    ("python", "java")
]

for s, t in test_cases:
    result = min_operations_to_substring(s, t)
    print(f"s='{s}', t='{t}' -> {result} operations")
s='abbpqr', t='bbxy' -> 2 operations
s='hello', t='lo' -> 0 operations
s='python', t='java' -> 4 operations

Conclusion

The algorithm works by checking all possible substrings of s with the same length as t and counting character mismatches. The time complexity is O(n×k) where n is the length of s and k is the length of t.

Updated on: 2026-03-25T10:34:56+05:30

745 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements