Facebook Pixel

1217. Minimum Cost to Move Chips to The Same Position

Problem Description

You are given n chips where each chip has a position specified in the array position[i].

The goal is to move all chips to the same position with minimum cost. You can move chips according to these rules:

  • Moving a chip by 2 positions (either position[i] + 2 or position[i] - 2) costs 0
  • Moving a chip by 1 position (either position[i] + 1 or position[i] - 1) costs 1

The key insight is that chips can be moved by any even distance for free (cost = 0), while moving by an odd distance always costs 1. This means:

  • All chips at even positions can be moved to any other even position for free
  • All chips at odd positions can be moved to any other odd position for free
  • Moving a chip from an even position to an odd position (or vice versa) costs 1

The solution counts how many chips are at odd positions (a) and how many are at even positions (b). Since we can gather all odd-positioned chips at one odd position for free, and all even-positioned chips at one even position for free, the minimum cost is simply moving the smaller group to join the larger group. Each chip in the smaller group costs 1 to move to the opposite parity position.

Therefore, the answer is min(a, b) where a is the count of chips at odd positions and b is the count of chips at even positions.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The first observation is that moving a chip by 2 positions costs nothing. This means we can move a chip by any even distance (4, 6, 8, etc.) for free by repeatedly moving it by 2.

This leads to a crucial insight: the actual positions don't matter - what matters is whether each position is odd or even. Why? Because:

  • Any chip at an even position (like 2, 4, 6, 100) can reach any other even position for free
  • Any chip at an odd position (like 1, 3, 5, 99) can reach any other odd position for free

Think of it this way: positions can be grouped into two categories based on their parity (odd or even). Within each category, chips can move freely to any position in that same category.

Since moving by 1 position costs 1, this is the only way to change from even to odd (or odd to even). A chip must pay cost 1 to switch between these two groups.

Now the problem becomes much simpler: we have two groups of chips (odd-positioned and even-positioned), and we need to merge them into one group. We can either:

  1. Move all odd-positioned chips to an even position (costs = number of odd-positioned chips)
  2. Move all even-positioned chips to an odd position (costs = number of even-positioned chips)

Naturally, we choose the option with fewer moves, which means moving the smaller group to join the larger group. This is why the answer is simply min(count_odd, count_even).

Learn more about Greedy and Math patterns.

Solution Approach

The implementation follows directly from our understanding that we need to count chips at odd and even positions.

Step 1: Count chips at odd positions

We iterate through the position array and count how many chips are at odd positions using p % 2. When a position is odd, p % 2 equals 1, and when it's even, p % 2 equals 0. The sum gives us the total count of chips at odd positions:

a = sum(p % 2 for p in position)

Step 2: Count chips at even positions

Since we know the total number of chips is len(position), and we've already counted odd-positioned chips, the number of even-positioned chips is simply:

b = len(position) - a

Step 3: Find the minimum cost

As discussed, we want to move the smaller group to join the larger group. The cost equals the size of the smaller group:

return min(a, b)

The algorithm uses:

  • Time Complexity: O(n) where n is the number of chips, as we iterate through the position array once
  • Space Complexity: O(1) as we only use two variables to store counts

The pattern here is a greedy approach - we make the locally optimal choice (move the smaller group) which leads to the globally optimal solution.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through an example with position = [2, 2, 3, 3, 3].

Step 1: Identify chip positions and their parities

  • Chip at position 2: even
  • Chip at position 2: even
  • Chip at position 3: odd
  • Chip at position 3: odd
  • Chip at position 3: odd

Step 2: Count chips by parity

  • Chips at odd positions: 3 (all the chips at position 3)
  • Chips at even positions: 2 (all the chips at position 2)

Step 3: Understand free movements

  • The 2 chips at position 2 can move to ANY even position for free (e.g., to position 0, 4, 6, 100, etc.)
  • The 3 chips at position 3 can move to ANY odd position for free (e.g., to position 1, 5, 7, 99, etc.)

Step 4: Calculate minimum cost We have two options:

  1. Move all 3 odd-positioned chips to an even position → Cost = 3
  2. Move all 2 even-positioned chips to an odd position → Cost = 2

The minimum cost is min(3, 2) = 2.

Step 5: Verify with a concrete move sequence Let's say we decide to move all chips to position 3:

  • Chips already at position 3: stay (cost = 0)
  • Chip at position 2 → position 3: move by 1 (cost = 1)
  • Chip at position 2 → position 3: move by 1 (cost = 1)
  • Total cost = 2 ✓

Alternatively, we could move all chips to position 1:

  • Chips at position 3 → position 1: move by 2 (cost = 0 for each)
  • Chips at position 2 → position 1: move by 1 (cost = 1 for each)
  • Total cost = 2 ✓

The beauty of this solution is that we don't need to determine the exact final position - we just need to count chips by parity and move the smaller group!

Solution Implementation

1class Solution:
2    def minCostToMoveChips(self, position: List[int]) -> int:
3        # Count chips at odd positions
4        odd_position_count = sum(chip_pos % 2 for chip_pos in position)
5      
6        # Count chips at even positions
7        even_position_count = len(position) - odd_position_count
8      
9        # Return minimum cost: move all odd chips to even position or vice versa
10        # Moving between same parity positions (odd to odd or even to even) costs 0
11        # Moving between different parity positions (odd to even or even to odd) costs 1
12        return min(odd_position_count, even_position_count)
13
1class Solution {
2    public int minCostToMoveChips(int[] position) {
3        // Count chips at odd positions
4        int chipsAtOddPositions = 0;
5      
6        // Iterate through all chip positions
7        for (int chipPosition : position) {
8            // If position is odd, increment counter
9            chipsAtOddPositions += chipPosition % 2;
10        }
11      
12        // Calculate chips at even positions
13        int chipsAtEvenPositions = position.length - chipsAtOddPositions;
14      
15        // Return minimum cost: move either all odd-positioned chips to even positions
16        // or all even-positioned chips to odd positions
17        return Math.min(chipsAtOddPositions, chipsAtEvenPositions);
18    }
19}
20
1class Solution {
2public:
3    int minCostToMoveChips(vector<int>& position) {
4        // Count the number of chips at odd positions
5        int oddPositionCount = 0;
6        for (const auto& chipPosition : position) {
7            // Check if position is odd using bitwise AND with 1
8            // If the least significant bit is 1, the number is odd
9            oddPositionCount += chipPosition & 1;
10        }
11      
12        // Calculate the number of chips at even positions
13        int evenPositionCount = position.size() - oddPositionCount;
14      
15        // The minimum cost is to move all chips from the minority group
16        // (either odd or even positions) to the majority group
17        // Each such move costs 1 unit
18        return min(oddPositionCount, evenPositionCount);
19    }
20};
21
1/**
2 * Calculates the minimum cost to move all chips to the same position.
3 * Moving a chip by 2 positions costs 0, moving by 1 position costs 1.
4 * Strategy: Group chips by parity (odd/even positions), then move the smaller group.
5 * 
6 * @param position - Array of integers representing the initial positions of chips
7 * @returns The minimum cost to move all chips to the same position
8 */
9function minCostToMoveChips(position: number[]): number {
10    // Count the number of chips at odd positions
11    let oddsCount: number = 0;
12  
13    for (const chipPosition of position) {
14        // If position is odd, increment the counter
15        oddsCount += chipPosition % 2;
16    }
17  
18    // Calculate the number of chips at even positions
19    let evensCount: number = position.length - oddsCount;
20  
21    // Return the minimum between odd and even counts
22    // This represents moving the smaller group to the larger group's parity
23    return Math.min(oddsCount, evensCount);
24}
25

Time and Space Complexity

The time complexity is O(n), where n is the number of chips (length of the position list). This is because the algorithm iterates through the position list once to calculate the sum of positions with odd indices using sum(p % 2 for p in position), which requires examining each element exactly once.

The space complexity is O(1) as the algorithm only uses two additional variables a and b to store intermediate results, regardless of the input size. The generator expression p % 2 for p in position is evaluated lazily and doesn't create an additional list in memory.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

Pitfall 1: Misunderstanding the Movement Rules

The Problem: Many people initially interpret the problem as needing to physically move chips step by step, calculating costs for each intermediate move. They might try to find an optimal target position and calculate the total cost of moving each chip to that specific position.

Why It Happens: The problem statement mentions specific movement costs (+2/-2 costs 0, +1/-1 costs 1), which can lead to overthinking about pathfinding or optimal positioning.

The Solution: Recognize that the key insight is about parity (odd vs even positions). Since we can move by any even distance for free (by chaining +2 or -2 moves), the only cost that matters is changing parity. This transforms the problem from a complex positioning problem to a simple counting problem.

Pitfall 2: Attempting to Find the Optimal Target Position

The Problem: Some solutions try to determine which specific position all chips should move to, testing different positions as potential gathering points and calculating costs for each.

# Incorrect approach - unnecessarily complex
def minCostToMoveChips(position):
    min_cost = float('inf')
    for target in set(position):  # Try each unique position
        cost = 0
        for pos in position:
            distance = abs(pos - target)
            cost += distance % 2  # Cost is 1 if odd distance
        min_cost = min(min_cost, cost)
    return min_cost

Why It Happens: It seems logical that we need to pick a specific position where all chips will gather.

The Solution: Realize that the exact target position doesn't matter - only whether it's odd or even. All odd positions are equivalent (reachable from any other odd position at no cost), and all even positions are equivalent. The optimal strategy is simply to gather all chips at positions of the same parity, choosing the parity that requires fewer chips to change.

Pitfall 3: Overcomplicating the Parity Check

The Problem: Using unnecessarily complex conditions to check if a number is odd or even.

# Overly complex
odd_count = 0
for pos in position:
    if pos & 1 == 1:  # Using bitwise operation
        odd_count += 1
  
# Or using division
for pos in position:
    if pos / 2 != pos // 2:  # Checking if divisible by 2
        odd_count += 1

The Solution: Keep it simple with the modulo operator:

odd_count = sum(pos % 2 for pos in position)

This is cleaner, more readable, and directly expresses the intent of counting odd positions.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

What is an advantages of top-down dynamic programming vs bottom-up dynamic programming?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More