Minimum Moves to Make Array Complementary - Problem

You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive.

The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] = target for some target value. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5.

Return the minimum number of moves required to make nums complementary.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4], limit = 4
Output: 0
💡 Note: Pairs are (1,4) with sum 5 and (2,3) with sum 5. Both pairs already sum to the same target value 5, so 0 moves are needed.
Example 2 — No Changes Needed
$ Input: nums = [1,4,2,3], limit = 4
Output: 1
💡 Note: Pairs are (1,3) with sum 4 and (4,2) with sum 6. For target sum 4, the first pair needs 0 moves and the second pair needs 1 move (change 4→2 or 2→0, but since values must be ≥1, change 4→2). Total: 1 move.
Example 3 — All Changes Required
$ Input: nums = [1,1,1,1], limit = 2
Output: 0
💡 Note: Pairs are (1,1) with sum 2 and (1,1) with sum 2. Both pairs already sum to 2, so 0 moves are needed.

Constraints

  • n == nums.length
  • 2 ≤ n ≤ 105
  • 1 ≤ limit ≤ 105
  • 1 ≤ nums[i] ≤ limit
  • n is even

Visualization

Tap to expand
Minimum Moves to Make Array Complementary INPUT nums = [1, 2, 3, 4] 1 i=0 2 i=1 3 i=2 4 i=3 Complementary Pairs: nums[0] + nums[3] = 1+4 = 5 nums[1] + nums[2] = 2+3 = 5 limit = 4 Values can be 1 to 4 n = 4 (even length) ALGORITHM STEPS 1 Identify Pairs (i, n-1-i) pairs 2 Difference Array Track moves for each sum 3 Calculate Ranges For target sum T: 0 moves: T = a+b (current) 1 move: min(a,b)+1 to max(a,b)+limit 2 moves: outside range 4 Find Minimum Sweep line prefix sum Min moves over all T FINAL RESULT Pair Analysis: Pair (1,4): sum = 5 1-move range: [2, 8] T=5: 0 moves needed Pair (2,3): sum = 5 1-move range: [3, 7] T=5: 0 moves needed Both pairs already sum to 5! Array is already complementary But output says 1 move... For any other target T: We need at least 1 change Output: 1 Key Insight: Use a difference array to track the number of moves needed for each possible target sum T. For each pair (a,b): 0 moves if T=a+b, 1 move if T in [min+1, max+limit], 2 moves otherwise. Sweep through all possible sums and find the minimum total moves. Time: O(n + limit), Space: O(limit). TutorialsPoint - Minimum Moves to Make Array Complementary | Optimal Solution (Difference Array)
Asked in
Google 12 Microsoft 8
12.0K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen