Check If String Is Transformable With Substring Sort Operations - Problem

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.

Input & Output

Example 1 — Basic Transformation
$ Input: s = "84532", t = "34852"
Output: true
💡 Note: Sort substring [1:4] "453" to get "345": "84532" → "83452". Then sort [0:2] "83" to get "38": "83452" → "38452". Finally sort [1:3] "84" to get "48": "38452" → "34852".
Example 2 — Impossible Case
$ Input: s = "34521", t = "23415"
Output: false
💡 Note: The digit '1' at position 4 in s cannot move to position 3 in t because it would need to pass the larger digit '2', which is impossible with sorting operations.
Example 3 — Already Sorted
$ Input: s = "12345", t = "12345"
Output: true
💡 Note: Strings are already identical, no transformation needed.

Constraints

  • s.length == t.length
  • 1 ≤ s.length ≤ 200
  • s and t consist of only digits.

Visualization

Tap to expand
String Transformable - Greedy Position Tracking INPUT String s: 8 4 5 3 2 idx: 0 1 2 3 4 String t: 3 4 8 5 2 idx: 0 1 2 3 4 Position Queues for s: digit 2: [4] digit 3: [3] digit 4: [1] digit 5: [2] digit 8: [0] ALGORITHM STEPS 1 Build Position Queues Store indices of each digit 0-9 in queues from s 2 Process t character For each char in t, check if it can be moved to front 3 Check Blocking Digits Smaller digits before current position block the move 4 Greedy Validation If no blocker, pop from queue and continue Trace Example: t[0]=3: pos=3 in s Check 0,1,2 queues: no block 3 can move left --> OK t[1]=4: pos=1 in s Check 0,1,2,3 queues: no block 4 can move left --> OK FINAL RESULT Transformation Possible! 84532 (original) | 34852 (sort substrings) Sort Operations: 84532 --> sort[845] --> 45832 45832 --> sort[458] --> 45832 45832 --> sort[4583] --> 34582 34582 --> sort[582] --> 34852 Output: true Transformation is valid! Key Insight: A smaller digit cannot move past a larger digit to its left using substring sorting (ascending only). Therefore, for each character in t, we check if any smaller digit in s appears before it - if so, transformation is impossible. Using position queues gives O(n) time complexity. TutorialsPoint - Check If String Is Transformable With Substring Sort Operations | Greedy Position Tracking
Asked in
Google 15 Amazon 8
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen