Talentd
FleetCode
Make and follow sheets.Sign in

Split and Merge Array Transformation solution and explanation

MediumArrayBreadth-First SearchHash Table5 min read58.7% acceptanceUpdated 24 Mar 2026
Split and Merge Array Transformation | LeetCode 3690 | Weekly Contest 468Sanyam IIT Guwahati · 18:03 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. Split and Merge Array Transformation | LeetCode 3690 | Weekly Contest 468Sanyam IIT Guwahati · 18:03 · 2K views
  2. Leetcode 3690 | Split and Merge Array Transformation Detailed Explanation & Dry run | Contest 468 Q3Samrat Bhardwaj · 40:16 · 689 views
  3. 3690. Split and Merge Array Transformation (Leetcode Medium)Programming Live with Larry · 20:41 · 613 views
  4. Weekly Contest 468 🔥 LeetCode 3690 (Q3) | Split and Merge Array Transformations | BFS + Set Solution Study Placement · 29:47 · 558 views
  5. Split and Merge Array Transformation | Weekly Contest 468 | Q3 | BFS IntuitionExpertFunda · 9:11 · 555 views
  6. Split and Merge Array Transformation | Detailed Thought Process | Leetcode 3660 |Simple ExplanationCodeWith_Kedar · 14:47 · 532 views
  7. Leetcode 3690 | Split and Merge Array TransformationCodeWithMeGuys · 13:01 · 493 views
  8. Leetcode | 3690 Split and Merge Array Transformation | Java | Weekly ContestCakot Coding · 24:39 · 362 views
  9. 3690. Split and Merge Array Transformation | LeetCode 3690 | LeetCode Weekly Contest 468 | Q3deep_dive_coding · 20:51 · 117 views
  10. 3690. Split and Merge Array Transformation | Leetcode Weekly Contest 468Break and Build · 40:51 · 92 views

The problem

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.

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].
  • Insert [3] at the end; the array becomes [1,2,3].

Example 2:

Input: nums1 = [1,1,2,3,4,5], nums2 = [5,4,3,2,1,1]

Output: 3

Explanation:

  • 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.

Approach overview

Problem Overview: You are given an array and a set of allowed operations that split elements or merge adjacent elements. The goal is to determine whether one configuration can be transformed into another using these operations. Each transformation creates a new array state, so the task becomes exploring valid states efficiently without revisiting duplicates.

Approach 1: Brute Force State Simulation (Exponential Time, High Space)

The most direct idea is to simulate every possible sequence of split and merge operations. At each step, iterate through the array, attempt all valid splits and merges, and generate new arrays. This quickly explodes because each operation creates multiple branches. Without tracking visited states, the same configuration appears repeatedly. Time complexity grows exponentially with the number of operations, and space complexity is also exponential due to storing intermediate states.

Approach 2: Breadth-First Search with Hash Set (Optimal BFS Traversal)

Treat each array configuration as a node in a graph. An edge exists between two nodes if one can be obtained from the other via a single split or merge operation. Use Breadth-First Search to explore states level by level starting from the initial array. Each generated configuration is encoded (for example as a string or tuple) and stored in a visited hash table to prevent reprocessing duplicates.

During BFS, generate neighbors by iterating through the array and applying valid split or merge operations. Push unseen states into a queue. If the target configuration appears, the transformation is possible. BFS guarantees the shortest sequence of operations if the problem asks for minimum steps. Time complexity depends on the number of reachable states but is typically expressed as O(S * N), where S is the number of unique states explored and N is the array length. Space complexity is O(S) for the queue and visited set.

This approach works well because each state is processed once and duplicate configurations are eliminated using hashing. Arrays are naturally modeled as nodes in a state graph, making BFS the most natural traversal strategy when exploring transformation sequences involving arrays.

Recommended for interviews: Start by explaining the brute force simulation to demonstrate understanding of the operations and the search space. Then transition to the BFS state‑graph model with a visited hash set. Interviewers usually expect the BFS approach because it systematically explores transformations while avoiding repeated work.

Solution

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 q to store the current array states, and use a set vis to record the visited array states to avoid duplicate computations. Initially, the queue contains only the array nums1.

Then, we perform the following steps:

  1. Remove the current array state cur from the queue.
  2. If cur equals the target array nums2, return the current number of operations.
  3. Otherwise, enumerate all possible split positions (l, r), remove the subarray cur[l..r] to obtain the remaining array remain and the subarray sub.
  4. Insert the subarray sub into all possible positions of the remaining array remain to generate new array states nxt.
  5. If a new array state nxt has not been visited, add it to the queue and the visited set.
  6. 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.

class Solution:
    def minSplitMerge(self, nums1: List[int], nums2: List[int]) -> int:
        n = len(nums1)
        target = tuple(nums2)
        start = tuple(nums1)

        q = [start]
        vis = set()
        vis.add(start)

        for ans in count(0):
            t = q
            q = []
            for cur in t:
                if cur == target:
                    return ans
                for l in range(n):
                    for r in range(l, n):
                        remain = list(cur[:l]) + list(cur[r + 1 :])
                        sub = cur[l : r + 1]
                        for i in range(len(remain) + 1):
                            nxt = tuple(remain[:i] + list(sub) + remain[i:])
                            if nxt not in vis:
                                vis.add(nxt)
                                q.append(nxt)
class Solution {
    public int minSplitMerge(int[] nums1, int[] nums2) {
        int n = nums1.length;
        List<Integer> target = toList(nums2);
        List<Integer> start = toList(nums1);
        List<List<Integer>> q = List.of(start);
        Set<List<Integer>> vis = new HashSet<>();
        vis.add(start);
        for (int ans = 0;; ++ans) {
            var t = q;
            q = new ArrayList<>();
            for (var cur : t) {
                if (cur.equals(target)) {
                    return ans;
                }
                for (int l = 0; l < n; ++l) {
                    for (int r = l; r < n; ++r) {
                        List<Integer> remain = new ArrayList<>();
                        for (int i = 0; i < l; ++i) {
                            remain.add(cur.get(i));
                        }
                        for (int i = r + 1; i < n; ++i) {
                            remain.add(cur.get(i));
                        }
                        List<Integer> sub = cur.subList(l, r + 1);
                        for (int i = 0; i <= remain.size(); ++i) {
                            List<Integer> nxt = new ArrayList<>();
                            for (int j = 0; j < i; ++j) {
                                nxt.add(remain.get(j));
                            }
                            for (int x : sub) {
                                nxt.add(x);
                            }
                            for (int j = i; j < remain.size(); ++j) {
                                nxt.add(remain.get(j));
                            }
                            if (vis.add(nxt)) {
                                q.add(nxt);
                            }
                        }
                    }
                }
            }
        }
    }

    private List<Integer> toList(int[] arr) {
        List<Integer> res = new ArrayList<>(arr.length);
        for (int x : arr) {
            res.add(x);
        }
        return res;
    }
}
class Solution {
public:
    int minSplitMerge(vector<int>& nums1, vector<int>& nums2) {
        int n = nums1.size();
        vector<int> target = nums2;
        vector<vector<int>> q{nums1};
        set<vector<int>> vis;
        vis.insert(nums1);

        for (int ans = 0;; ++ans) {
            vector<vector<int>> t = q;
            q.clear();
            for (auto& cur : t) {
                if (cur == target) {
                    return ans;
                }
                for (int l = 0; l < n; ++l) {
                    for (int r = l; r < n; ++r) {
                        vector<int> remain;
                        remain.insert(remain.end(), cur.begin(), cur.begin() + l);
                        remain.insert(remain.end(), cur.begin() + r + 1, cur.end());
                        vector<int> sub(cur.begin() + l, cur.begin() + r + 1);
                        for (int i = 0; i <= (int) remain.size(); ++i) {
                            vector<int> nxt;
                            nxt.insert(nxt.end(), remain.begin(), remain.begin() + i);
                            nxt.insert(nxt.end(), sub.begin(), sub.end());
                            nxt.insert(nxt.end(), remain.begin() + i, remain.end());

                            if (!vis.count(nxt)) {
                                vis.insert(nxt);
                                q.push_back(nxt);
                            }
                        }
                    }
                }
            }
        }
    }
};
func minSplitMerge(nums1 []int, nums2 []int) int {
	n := len(nums1)

	toArr := func(nums []int) [6]int {
		var t [6]int
		for i, x := range nums {
			t[i] = x
		}
		return t
	}

	start := toArr(nums1)
	target := toArr(nums2)

	vis := map[[6]int]bool{start: true}
	q := [][6]int{start}

	for ans := 0; ; ans++ {
		nq := [][6]int{}
		for _, cur := range q {
			if cur == target {
				return ans
			}
			for l := 0; l < n; l++ {
				for r := l; r < n; r++ {
					remain := []int{}
					for i := 0; i < l; i++ {
						remain = append(remain, cur[i])
					}
					for i := r + 1; i < n; i++ {
						remain = append(remain, cur[i])
					}

					sub := []int{}
					for i := l; i <= r; i++ {
						sub = append(sub, cur[i])
					}

					for pos := 0; pos <= len(remain); pos++ {
						nxtSlice := []int{}
						nxtSlice = append(nxtSlice, remain[:pos]...)
						nxtSlice = append(nxtSlice, sub...)
						nxtSlice = append(nxtSlice, remain[pos:]...)

						nxt := toArr(nxtSlice)
						if !vis[nxt] {
							vis[nxt] = true
							nq = append(nq, nxt)
						}
					}
				}
			}
		}
		q = nq
	}
}
Try this approach in the editor

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force SimulationExponentialExponentialUseful for understanding all possible operations or when constraints are extremely small
BFS with Hash Set (State Graph)O(S * N)O(S)General case where many transformations exist and duplicate states must be avoided
BFS with PruningO(S * N)O(S)When additional constraints allow pruning impossible states early

Frequently asked questions

Is Split and Merge Array Transformation easy or hard?

Split and Merge Array Transformation is typically classified as a Medium difficulty problem. The operations themselves are straightforward, but recognizing the state-space search and implementing BFS with proper state encoding and deduplication adds complexity.

Split and Merge Array Transformation Python/Java solution

Implement the BFS approach by storing the starting array in a queue and generating new arrays through valid split and merge operations. Encode each array state as a tuple (Python) or string (Java) to store in a hash set for fast duplicate detection. Continue exploring until the target configuration is found or all states are exhausted.

How to solve Split and Merge Array Transformation in O(n)?

A strict O(n) solution generally does not exist because the problem requires exploring multiple transformation states. The closest practical approach is BFS with hashing, which avoids revisiting duplicate arrays. By pruning repeated states and invalid transitions, the search becomes manageable for typical constraints.

What is the best approach for Split and Merge Array Transformation?

The most effective approach models the problem as a state graph and uses Breadth-First Search (BFS). Each array configuration is treated as a node, and split or merge operations generate neighboring states. A hash set stores visited configurations to avoid duplicates. This ensures every reachable configuration is processed at most once.

Is Split and Merge Array Transformation asked at Google/Amazon/Meta?

Array transformation problems combined with BFS state exploration frequently appear in interviews at companies like Google, Amazon, and Meta. Variants involve transforming strings, arrays, or graphs using minimal operations. The key skill being tested is recognizing the state-space search pattern and applying BFS efficiently.

What data structure is used in Split and Merge Array Transformation?

The core data structures are a queue for BFS traversal and a hash set for tracking visited states. Arrays represent the state itself, often encoded as tuples or strings for hashing. This combination ensures fast lookup and systematic exploration of transformation steps.

What is the time complexity of Split and Merge Array Transformation?

The BFS solution runs in O(S * N) time, where S is the number of unique array states explored and N is the array length. Each state requires generating possible split and merge operations across the array. Space complexity is O(S) because the queue and visited set store explored configurations.

Comments

Now write it yourselfClose this page and solve Split and Merge Array Transformation in the editor, without looking.
Practise Split and Merge Array Transformation