Minimum Moves to Make Array Complementary — LeetCode 1674 Python Solution

MediumArrayHash TablePrefix Sum
Problem
#1674
Pattern
Prefix Sum
Reading time
3 min

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

Example

Input
nums = [1,2,4,3], limit = 4
Output
1
Explanation
In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).

Python solution

Python
class Solution:
    def minMoves(self, nums: List[int], limit: int) -> int:
        d = [0] * (2 * limit + 2)
        n = len(nums)
        for i in range(n // 2):
            x, y = nums[i], nums[-i - 1]
            if x > y:
                x, y = y, x
            d[2] += 2
            d[x + 1] -= 2
            d[x + 1] += 1
            d[x + y] -= 1
            d[x + y + 1] += 1
            d[y + limit + 1] -= 1
            d[y + limit + 1] += 2
        return min(accumulate(d[2:]))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1674. Minimum Moves to Make Array Complementary is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1674. Minimum Moves to Make Array Complementary?
LeetCode 1674. Minimum Moves to Make Array Complementary is rated Medium on LeetCode.
What is the time complexity of LeetCode 1674. Minimum Moves to Make Array Complementary?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1674. Minimum Moves to Make Array Complementary?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1674. Minimum Moves to Make Array Complementary cover?
LeetCode 1674. Minimum Moves to Make Array Complementary is tagged Array, Hash Table and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview