[LeetCode] Split and Merge Array Transformation

3690. Split and Merge Array Transformation

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:

  1. Choose a subarray nums1[L..R].
  2. 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).
  3. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public:
int minSplitMerge(vector<int>& nums1, vector<int>& nums2) {
if(nums1 == nums2) return 0;
queue<vector<int>> q;
unordered_set<string> vis;
auto push = [&](vector<int>& A) {
string key = "";
for(auto& a : A) key += to_string(a) + "#";
if(!vis.count(key)) {
vis.insert(key);
q.push(A);
}
};
push(nums1);
int res = 0, n = nums1.size();
auto build = [](int cut, int until, int append, vector<int>& A) {
queue<int> q1, q2;
for(int i = 0; i < A.size(); i++) {
if(cut <= i and i <= until) q2.push(A[i]);
else q1.push(A[i]);
}
vector<int> res;
while(append--) {
res.push_back(q1.front()); q1.pop();
}
while(q2.size()) {
res.push_back(q2.front()); q2.pop();
}
while(q1.size()) {
res.push_back(q1.front()); q1.pop();
}
return res;
};
while(q.size()) {
int qsz = q.size();
while(qsz--) {
auto A = q.front(); q.pop();
for(int cut = 0; cut < n; cut++) {
for(int until = cut; until < n; until++) {
for(int append = 0; append < n - (until - cut + 1); append++) {
auto B = build(cut,until,append,A);
if(B == nums2) return res + 1;
push(B);
}
}
}
}
res++;
}
return -1;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/11/PS/LeetCode/split-and-merge-array-transformation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.