Program to check whether string Is transformable with substring sort operations in Python

When working with string transformations, we sometimes need to check if one numeric string can be transformed into another using substring sort operations. This problem involves selecting any substring and sorting it in ascending order to eventually match a target string.

The key insight is that when we sort a substring, smaller digits can move left past larger digits, but larger digits cannot move left past smaller digits that come after them in the original string.

Algorithm Approach

We use a greedy approach with position tracking ?

  • Store positions of each digit in reverse order (rightmost first)

  • For each digit in target string, check if it can be placed without violating constraints

  • A digit cannot be used if there's a smaller digit to its right that hasn't been used yet

Implementation

from collections import defaultdict

def solve(s, t):
    places = defaultdict(list)
    
    # Store positions of each digit in reverse order
    for i in reversed(range(len(s))):
        key = int(s[i])
        places[key].append(i)
    
    # Process each character in target string
    for e in t:
        key = int(e)
        
        # Check if digit is available
        if not places[key]:
            return False
        
        # Get rightmost available position
        i = places[key][-1]
        
        # Check constraint: no smaller unused digit should be to the right
        for j in range(key):
            if places[j] and places[j][-1] < i:
                return False
        
        # Use this position
        places[key].pop()
    
    return True

# Test the function
s = "95643"
t = "45963"
print(f"Can transform '{s}' to '{t}': {solve(s, t)}")

# Test with impossible transformation
s2 = "123"
t2 = "321"
print(f"Can transform '{s2}' to '{t2}': {solve(s2, t2)}")
Can transform '95643' to '45963': True
Can transform '123' to '321': False

How It Works

Let's trace through the example "95643" ? "45963" ?

String Transformation Process Original: 9 5 6 4 3 0 1 2 3 4 Target: 4 5 9 6 3 Positions: 3: [4] 4: [3] 5: [1] 6: [2] 9: [0] Processing Steps: 1. Need '4' at pos 3 ? 2. Need '5' at pos 1 ? 3. Need '9' at pos 0 ? 4. Need '6' at pos 2 ? 5. Need '3' at pos 4 ? Result: Transformation Possible

Key Points

  • We process digits from right to left to maintain sorting constraints

  • A digit can only be used if no smaller unused digit exists to its right

  • Time complexity: O(n × k) where n is string length and k is number of unique digits

  • Space complexity: O(n) for storing positions

Common Use Cases

This algorithm is useful for ?

  • String rearrangement problems with sorting constraints

  • Validating possible transformations in competitive programming

  • Checking feasibility of digit rearrangements

Conclusion

The algorithm uses position tracking and constraint checking to determine if a string transformation is possible through substring sorting operations. The key insight is that larger digits cannot move past smaller digits that appear later in the original string.

Updated on: 2026-03-26T14:11:24+05:30

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements