830. Scrambled Twins
A sign painter shuffles letters on a word board. A word is scrambled as follows: a word of length one stays as it is; otherwise cut it into a non-empty left part and a non-empty right part at any position, optionally swap the two parts, and then scramble each part independently by the same rule (each part may be cut and swapped again, or left alone).
Given the strings a and b, return true if some sequence of such cuts and swaps turns a into b, and false otherwise. Strings of different lengths can never match. Aim for time O(n^4) and space O(n^3), where n is the length.
Example 1
- Input:
- a = "harbor", b = "orbahr"
- Output:
- true
- Explanation:
Splitting and swapping pieces can turn the first word into the second, so the result is
true.
Example 2
- Input:
- a = "orchid", b = "oricdh"
- Output:
- false
- Explanation:
Both words use the same letters, yet no cut-and-swap sequence reaches this arrangement:
false.
Example 3
- Input:
- a = "lantern", b = "lanternn"
- Output:
- false
- Explanation:
The two words have different lengths, so no scrambling can match them:
false.
Constraints
0 ≤ a.length, b.length ≤ 50
a and b consist of lowercase English letters; if the lengths differ, the answer is false.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n^4)
- Space
- O(n^3)