You are given two integer arrays nums1 and nums2, each of length n. You may perform the following split-and-merge operation on nums1 any number of times:
Choose a subarray nums1[L..R].
Remove that subarray, leaving the prefix nums1[0..L-1] (empty if L = 0) and the suffix nums1[R+1..n-1] (empty if R = n - 1).
Re-insert the removed subarray (in its original order) at any position in the remaining array (i.e., between any two elements, at the very start, or at the very end).
Return the minimum number of split-and-merge operations needed to transform nums1 into nums2.
Example 1:
Input:nums1 = [3,1,2], nums2 = [1,2,3]
Output:1
Explanation:
Split out the subarray [3] (L = 0, R = 0); the remaining array is [1,2].
Remove [1,1,2] at indices 0 - 2; remaining is [3,4,5]; insert [1,1,2] at position 2, resulting in [3,4,1,1,2,5].
Remove [4,1,1] at indices 1 - 3; remaining is [3,2,5]; insert [4,1,1] at position 3, resulting in [3,2,5,4,1,1].
Remove [3,2] at indices 0 - 1; remaining is [5,4,1,1]; insert [3,2] at position 2, resulting in [5,4,3,2,1,1].
Constraints:
2 <= n == nums1.length == nums2.length <= 6
-105 <= nums1[i], nums2[i] <= 105
nums2 is a permutation of nums1.
Solutions
Solution 1: BFS
We can use Breadth-First Search (BFS) to solve this problem. Since the array length is at most 6, we can enumerate all possible split and merge operations to find the minimum number of operations.
First, we define a queue \(\textit{q}\) to store the current array states, and use a set \(\textit{vis}\) to record the visited array states to avoid duplicate computations. Initially, the queue contains only the array \(\textit{nums1}\).
Then, we perform the following steps:
Remove the current array state \(\textit{cur}\) from the queue.
If \(\textit{cur}\) equals the target array \(\textit{nums2}\), return the current number of operations.
Otherwise, enumerate all possible split positions \((l, r)\), remove the subarray \(\textit{cur}[l..r]\) to obtain the remaining array \(\textit{remain}\) and the subarray \(\textit{sub}\).
Insert the subarray \(\textit{sub}\) into all possible positions of the remaining array \(\textit{remain}\) to generate new array states \(\textit{nxt}\).
If a new array state \(\textit{nxt}\) has not been visited, add it to the queue and the visited set.
Repeat the above steps until the target array is found or the queue is empty.
The time complexity is \(O(n! \times n^4)\), and the space complexity is \(O(n! \times n)\), where \(n\) is the length of the array.