Minimum Cost to Move Chips to The Same Position (LeetCode 1217): Solution and Explanation

Easy
Array
Math
Greedy

Chips sit at integer positions. Moving a chip by 2 is free and moving it by 1 costs 1. Find the cheapest way to stack every chip on one position. The whole problem reduces to counting even and odd positions.

Intuition

Since a move of 2 costs nothing, a chip can travel to any position with the same parity for free. Distance stops mattering; only even versus odd does.

So gather all even chips on one even spot and all odd chips on a neighbouring odd spot, both for free. Now there are just two piles, one step apart.

Merging them means every chip in one pile pays 1. Pick the smaller pile to move.

No plan can do better: whatever the final position, every chip of the other parity must make at least one odd-length move, which costs at least 1.

Approach: Parity count

  1. Set even = odd = 0.
  2. For each position, increment even if it is divisible by 2, otherwise increment odd.
  3. Return min(even, odd).

Step-by-step example

position = [2,2,2,3,3]
  1. Chips at 2, 2, 2 are even: even = 3.
  2. Chips at 3, 3 are odd: odd = 2.
  3. Moving the odd pile onto 2 costs 2. Moving the even pile onto 3 would cost 3.
  4. The answer is min(3, 2) = 2.

Code: Python, Java, C++

1class Solution:
2    def minCostToMoveChips(self, position: List[int]) -> int:
3        even = odd = 0
4        for p in position:
5            if p % 2 == 0:
6                even += 1
7            else:
8                odd += 1
9        return min(even, odd)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the positions.

Space

O(1)

Only two counters.

Other approaches

Try every chip position as the target (time O(n^2), space O(1))

For each candidate position, add 1 for every chip whose parity differs from it, and keep the smallest total. It gives the same answer but checks n targets.

Common mistakes

  • Computing real distances. Positions go up to 10^9, and distance is irrelevant because 2-steps are free.
  • Thinking the target must be one of the chip positions. Any target works; only its parity matters.
  • Returning max instead of min. The smaller pile is the one that should pay.

Frequently asked questions

Why does only parity matter?

Moves of 2 are free and keep parity, so any chip reaches any same-parity position at no cost. Changing parity needs a 1-step, which costs 1.

Can a chip ever need to pay more than 1?

No. One 1-step changes its parity, and the rest of the trip is free 2-steps.

What if all chips share a parity?

Then one count is 0 and the answer is 0, since every chip can reach the same spot for free.