Minimum Cost to Move Chips to The Same Position

Easy

Topics
ArrayMathGreedy

Chips are at positions given by nums. Moving a chip by 2 costs 0; moving it by 1 costs 1. Return the minimum total cost to move all chips to the same position. Even and odd positions split into two groups, so the answer is the size of the smaller group.

Example 1

102132
Input:  position = [1,2,3]
Output: 1

Example 2

2021223334
Input:  position = [2,2,2,3,3]
Output: 2

Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

The cost rule is the whole problem: moving a chip by 2 is free, moving it by 1 costs 1. Free movement by 2 means a chip can reach any position of the same parity at no cost whatsoever.

So position barely matters — only parity does. Every chip on an even position can be gathered at one even spot for free; every chip on an odd position likewise. That reduces the board to two piles, and the only real cost is moving one entire pile across by 1 to join the other.

Therefore the answer is min(count_even, count_odd): move the smaller pile.

Approach

  1. Count chips on even positions.
  2. Return the smaller of that count and the rest.

Dry Run

positions = [2,2,2,3,3]

even positions: 2,2,2   -> 3 chips
odd  positions: 3,3     -> 2 chips

gather each pile for free, then move the smaller (2 chips) by 1
answer 2

positions = [1,1000000000]
even: 1 chip (1000000000)   odd: 1 chip (1)
answer 1

Complexity

  • Time — O(n): one counting pass.
  • Space — O(1): one counter. Note the positions themselves can be up to 10^9, which is irrelevant — only their parity is read, so no array sized by position is needed. Building one would be the trap.

Common Pitfalls

  • Trying to find an optimal target position. There is none to find; any position of the majority parity is equally good.
  • Allocating an array indexed by position. Positions reach 10^9 while the chip count is at most 100.
  • Summing distances. Movement by 2 is free, so distance does not enter the cost at all.
  • Returning the larger count, or the difference between the counts.

Full Solution — all languages

class Solution:
    def minCostToMoveChips(self, nums):
        even = sum(1 for x in nums if x % 2 == 0)
        return min(even, len(nums) - even)
SensAI
Beta
Tap the mic to stop voice mode