#1585
Check If String Is Transformable With Substring Sort Operations
HardStringGreedySortingTwo PointersSortingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the fact that we can only sort characters in 's' to match the order in 't' while maintaining their relative positions. We can use a two-pointer technique to check if we can match 't' by traversing 's'.
⚙️
Algorithm
3 steps- 1Step 1: Check if 's' and 't' are anagrams (same characters in different order).
- 2Step 2: Use two pointers to traverse both strings simultaneously.
- 3Step 3: For each character in 't', check if it can be found in 's' while maintaining the order and relative positions.
solution.py9 lines
1def canTransform(s, t):
2 if sorted(s) != sorted(t):
3 return False
4 s_pointer, t_pointer = 0, 0
5 while t_pointer < len(t):
6 if s_pointer < len(s) and s[s_pointer] == t[t_pointer]:
7 t_pointer += 1
8 s_pointer += 1
9 return t_pointer == len(t)ℹ
Complexity note: The time complexity is O(n) because we traverse the strings linearly. The space complexity is O(n) due to the storage used for counting characters in the anagram check.
- 1Sorting a substring does not change the overall character counts, so we must first check if both strings are anagrams.
- 2The order of characters can be maintained by ensuring we can find each character of 't' in 's' in the correct sequence.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.