Using greedy without proof
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Given two strings s and t, transform string s into string t using the following operation any number of times:
s and sort it in place so the characters are in ascending order.
"14234" results in "12344".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 <= 105s and t consist of only digits.Problem summary: 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 s and 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". 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Greedy
"84532" "34852"
"34521" "23415"
"12345" "12435"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1585: Check If String Is Transformable With Substring Sort Operations
class Solution {
public boolean isTransformable(String s, String t) {
Deque<Integer>[] pos = new Deque[10];
Arrays.setAll(pos, k -> new ArrayDeque<>());
for (int i = 0; i < s.length(); ++i) {
pos[s.charAt(i) - '0'].offer(i);
}
for (int i = 0; i < t.length(); ++i) {
int x = t.charAt(i) - '0';
if (pos[x].isEmpty()) {
return false;
}
for (int j = 0; j < x; ++j) {
if (!pos[j].isEmpty() && pos[j].peek() < pos[x].peek()) {
return false;
}
}
pos[x].poll();
}
return true;
}
}
// Accepted solution for LeetCode #1585: Check If String Is Transformable With Substring Sort Operations
func isTransformable(s string, t string) bool {
pos := [10][]int{}
for i, c := range s {
pos[c-'0'] = append(pos[c-'0'], i)
}
for _, c := range t {
x := int(c - '0')
if len(pos[x]) == 0 {
return false
}
for j := 0; j < x; j++ {
if len(pos[j]) > 0 && pos[j][0] < pos[x][0] {
return false
}
}
pos[x] = pos[x][1:]
}
return true
}
# Accepted solution for LeetCode #1585: Check If String Is Transformable With Substring Sort Operations
class Solution:
def isTransformable(self, s: str, t: str) -> bool:
pos = defaultdict(deque)
for i, c in enumerate(s):
pos[int(c)].append(i)
for c in t:
x = int(c)
if not pos[x] or any(pos[i] and pos[i][0] < pos[x][0] for i in range(x)):
return False
pos[x].popleft()
return True
// Accepted solution for LeetCode #1585: Check If String Is Transformable With Substring Sort Operations
struct Solution;
impl Solution {
fn is_transformable(s: String, t: String) -> bool {
let n = s.len();
let s: Vec<u8> = s.bytes().collect();
let t: Vec<u8> = t.bytes().collect();
let mut idx: Vec<Vec<usize>> = vec![vec![]; 10];
for i in (0..n).rev() {
idx[(s[i] - b'0') as usize].push(i);
}
for i in 0..n {
let k = (t[i] - b'0') as usize;
if idx[k].is_empty() {
return false;
}
let p = idx[k].pop().unwrap();
for j in 0..k {
if let Some(&q) = idx[j].last() {
if q < p {
return false;
}
}
}
}
true
}
}
#[test]
fn test() {
let s = "84532".to_string();
let t = "34852".to_string();
let res = true;
assert_eq!(Solution::is_transformable(s, t), res);
let s = "34521".to_string();
let t = "23415".to_string();
let res = true;
assert_eq!(Solution::is_transformable(s, t), res);
let s = "12345".to_string();
let t = "12435".to_string();
let res = false;
assert_eq!(Solution::is_transformable(s, t), res);
let s = "1".to_string();
let t = "2".to_string();
let res = false;
assert_eq!(Solution::is_transformable(s, t), res);
}
// Accepted solution for LeetCode #1585: Check If String Is Transformable With Substring Sort Operations
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1585: Check If String Is Transformable With Substring Sort Operations
// class Solution {
// public boolean isTransformable(String s, String t) {
// Deque<Integer>[] pos = new Deque[10];
// Arrays.setAll(pos, k -> new ArrayDeque<>());
// for (int i = 0; i < s.length(); ++i) {
// pos[s.charAt(i) - '0'].offer(i);
// }
// for (int i = 0; i < t.length(); ++i) {
// int x = t.charAt(i) - '0';
// if (pos[x].isEmpty()) {
// return false;
// }
// for (int j = 0; j < x; ++j) {
// if (!pos[j].isEmpty() && pos[j].peek() < pos[x].peek()) {
// return false;
// }
// }
// pos[x].poll();
// }
// return true;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.