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 Transformation with Substring Sorting84532Source: "84532"Sort operations34852Target: "34852"Key insight: Smaller digits can only move right during sortingResult: true (transformation possible)
Understanding the Visualization
1
Input
Source string s = "84532" and target t = "34852"
2
Transform
Apply substring sorting operations strategically
3
Validate
Check if transformation is possible using position constraints
Key Takeaway
🎯 Key Insight: Smaller digits can never move past larger digits during substring sorting operations
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