Minimum Cost to Move Chips to The Same Position — LeetCode 1217 Python Solution

EasyGreedyArrayMath
Problem
#1217
Pattern
Greedy
Reading time
2 min

The problem

We have n chips, where the position of the ith chip is position[i]. We need to move all the chips to the same position.

Example

Input
position = [1,2,3]
Output
1
Explanation
First step: Move the chip at position 3 to position 1 with cost = 0.

Python solution

Python
class Solution:
    def minCostToMoveChips(self, position: List[int]) -> int:
        a = sum(p % 2 for p in position)
        b = len(position) - a
        return min(a, b)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1217. Minimum Cost to Move Chips to The Same Position is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1217. Minimum Cost to Move Chips to The Same Position?
LeetCode 1217. Minimum Cost to Move Chips to The Same Position is rated Easy on LeetCode.
What is the time complexity of LeetCode 1217. Minimum Cost to Move Chips to The Same Position?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1217. Minimum Cost to Move Chips to The Same Position?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1217. Minimum Cost to Move Chips to The Same Position cover?
LeetCode 1217. Minimum Cost to Move Chips to The Same Position is tagged Greedy, Array and Math 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