#3690

Split and Merge Array Transformation

Medium
ArrayHash TableBreadth-First SearchHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use BFS to explore states of nums1, transforming it into nums2 by considering each split-and-merge operation as a state transition.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a queue with nums1 and a count of operations.
  2. 2Step 2: For each state, generate new states by removing subarrays and reinserting them in all possible positions.
  3. 3Step 3: If a new state matches nums2, return the operation count.
solution.py19 lines
1from collections import deque
2
3def min_operations(nums1, nums2):
4    queue = deque([(nums1, 0)])
5    seen = set()
6    while queue:
7        current, ops = queue.popleft()
8        if current == nums2:
9            return ops
10        for i in range(len(current)):
11            for j in range(i, len(current)):
12                sub = current[i:j+1]
13                remaining = current[:i] + current[j+1:]
14                for k in range(len(remaining) + 1):
15                    new_state = remaining[:k] + sub + remaining[k:]
16                    if tuple(new_state) not in seen:
17                        seen.add(tuple(new_state))
18                        queue.append((new_state, ops + 1))
19    return -1

Complexity note: BFS explores each state once, leading to linear complexity in terms of operations.

  • 1BFS is effective for state exploration.
  • 2Tracking seen states prevents cycles.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.