Check If String Is Transformable With Substring Sort Operations Problem
Description
LeetCode Problem 1585.
Given two strings s and t, transform string s into string t using the following operation any number of times:
- Choose a non-empty substring in
sand sort it in place so the characters are in ascending order.- For example, applying the operation on the underlined substring in
"14234"results in"12344".
- For example, applying the operation on the underlined substring in
Return true if it is possible to transform s into t. Otherwise, return false.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "84532", t = "34852"
Output: true
Explanation: You can transform s into t using the following sort operations:
"84532" (from index 2 to 3) -> "84352"
"84352" (from index 0 to 2) -> "34852"
Example 2:
Input: s = "34521", t = "23415"
Output: true
Explanation: You can transform s into t using the following sort operations:
"34521" -> "23451"
"23451" -> "23415"
Example 3:
Input: s = "12345", t = "12435"
Output: false
Constraints:
s.length == t.length1 <= s.length <= 10^5sandtconsist of only digits.
Solution
Approach: Digit Position Queues
Sorting a substring can be done by a series of swaps of adjacent pairs that are out of order (bubble sort), and any such swap is itself a sort of a length-2 substring. So the operation is the same as: swap two adjacent digits when the left one is larger. In other words, a digit can move left only by jumping over larger digits; it can never pass a smaller one.
Build t from left to right. The next character of t is some digit x, and it must come from the leftmost unused x in s (using a later copy would mean two equal digits crossing each other, which gains nothing). Let that copy be at index i. It can move to the front of what is left only if no unused digit smaller than x sits before i. So:
- Keep, for each digit, the list of its indices in
sand a pointer to the first unused one. - For each
xint: if noxis left, returnfalse(the digit counts differ). If somed < xhas an unused index smaller thani, returnfalse. Otherwise mark thisxas used.
If all of t is placed, return true. Each step checks at most 10 digits.
Complexity: O(10 n) time and O(n) extra space for the index lists.
class Solution:
def isTransformable(self, s: str, t: str) -> bool:
pos = [[] for _ in range(10)] # indices of each digit in s, in increasing order
for i, c in enumerate(s):
pos[int(c)].append(i)
head = [0] * 10 # how many indices of each digit are already used
for c in t:
x = int(c)
if head[x] == len(pos[x]):
return False # t has more of digit x than s
i = pos[x][head[x]]
# x can only move left past larger digits: no unused smaller digit may sit before it
for d in range(x):
if head[d] < len(pos[d]) and pos[d][head[d]] < i:
return False
head[x] += 1
return True