Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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" ?
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.
