#1674

Minimum Moves to Make Array Complementary

Medium
ArrayHash TablePrefix SumHash 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)

The optimal solution uses a frequency array to track how many modifications are needed for each potential target sum. This reduces the complexity by avoiding repeated calculations for each target sum.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a frequency array to count the number of moves needed for each possible sum from 2 to 2 * limit.
  2. 2Step 2: For each pair (nums[i], nums[n-1-i]), update the frequency array based on how many moves are needed to achieve each target sum.
  3. 3Step 3: Calculate the cumulative moves needed for each target sum and find the minimum.
solution.py18 lines
1# Full working Python code
2
3def minMoves(nums, limit):
4    n = len(nums)
5    moves = [0] * (2 * limit + 2)
6    for i in range(n // 2):
7        a, b = nums[i], nums[n - 1 - i]
8        low = max(2, a + b)
9        high = min(2 * limit, a + b)
10        moves[low] += 1
11        moves[high + 1] -= 1
12    min_moves = float('inf')
13    current_moves = 0
14    for target in range(2, 2 * limit + 1):
15        current_moves += moves[target]
16        min_moves = min(min_moves, current_moves)
17    return min_moves
18

Complexity note: The time complexity is O(n) because we only iterate through the array a constant number of times, and the space complexity is O(n) due to the frequency array used to track modifications.

  • 1Understanding how to pair elements and their sums is crucial for this problem.
  • 2Using a frequency array can significantly optimize the solution by reducing the number of calculations.

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