Minimum Cost to Move Chips to The Same Position
EasyPrompt
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. In one step, we can change the position of the ith chip from position[i] to:
position[i] + 2orposition[i] - 2withcost = 0.position[i] + 1orposition[i] - 1withcost = 1.
Return the minimum cost needed to move all the chips to the same position.
Example 1:
Input: position = [1,2,3]
Output: 1
Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.Example 2:
Input: position = [2,2,2,3,3]
Output: 2
Explanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.Example 3:
Input: position = [1,1000000000]
Output: 1
Constraints:
1 <= position.length <= 1001 <= position[i] <= 10^9
Approaches
2 approaches with complexity analysis and trade-offs.
This approach simulates the process of moving chips for every possible target position. A key observation is that we don't need to check every integer as a potential target. The optimal target position will have the same parity as one of the groups (even or odd) of the initial chip positions. Therefore, we only need to test the positions where chips are already located.
We can iterate through each chip's initial position and consider it as the final destination for all other chips. For each potential destination, we calculate the total cost required to move every chip to that spot. The minimum of these total costs will be our answer.
Algorithm
- Initialize
minCostto infinity. - For each position
p1in the input arrayposition:- Set
p1as thetargetPosition. - Initialize
currentCostto 0. - For each position
p2in thepositionarray:- Calculate the cost to move from
p2totargetPosition. The cost is 1 ifp2andtargetPositionhave different parities, and 0 otherwise. - Add this cost to
currentCost.
- Calculate the cost to move from
- Update
minCost = min(minCost, currentCost).
- Set
- Return
minCost.
Walkthrough
The algorithm works as follows:
- Initialize a variable
minCostto a very large value (e.g.,Integer.MAX_VALUE). - Iterate through each position
p1in thepositionarray. Thisp1will serve as the potential target position for all chips. - For each
p1, calculate the cost to move all chips to this position.- Initialize a
currentCostto 0. - Iterate through every other position
p2in thepositionarray. - The cost to move a chip from
p2top1is determined by the parity of the distance between them. A move of 2 units is free, and a move of 1 unit costs 1. This means the cost isabs(p1 - p2) % 2. - Add this cost to
currentCost.
- Initialize a
- After calculating the
currentCostfor the targetp1, compare it withminCostand updateminCostifcurrentCostis smaller. - After iterating through all positions in the input array as potential targets,
minCostwill hold the minimum possible cost.
Here is a code snippet demonstrating this approach:
class Solution { public int minCostToMoveChips(int[] position) { int n = position.length; if (n <= 1) { return 0; } int minCost = Integer.MAX_VALUE; // Iterate through each position as a potential target for (int i = 0; i < n; i++) { int targetPos = position[i]; int currentCost = 0; // Calculate the cost to move all chips to targetPos for (int j = 0; j < n; j++) { int chipPos = position[j]; // Cost is 1 if parities differ, 0 otherwise. // This is equivalent to abs(chipPos - targetPos) % 2 if ((chipPos % 2) != (targetPos % 2)) { currentCost++; } } minCost = Math.min(minCost, currentCost); } return minCost; }}Complexity
Time
O(N^2), where N is the number of chips. We have a nested loop, where both loops iterate up to N times.
Space
O(1). We only use a few variables to store the costs and loop indices, not dependent on the input size.
Trade-offs
Pros
Simple to understand and implement.
It correctly solves the problem by exploring a sufficient subset of possible target positions.
Cons
Inefficient for large inputs due to the quadratic time complexity.
It performs many redundant calculations since the cost only depends on the parity of the target, not its specific value.
A more insightful analysis of the move costs reveals a much simpler solution. Moving a chip by an even number of steps (e.g., pos -> pos + 2k) has a cost of 0. Moving a chip by an odd number of steps (e.g., pos -> pos + 2k + 1) has a cost of 1. This is because any move of an odd distance can be broken down into one move of distance 1 (cost 1) and some number of moves of distance 2 (cost 0).
This means that moving a chip between two positions of the same parity (even to even, or odd to odd) is always free. The only time a cost is incurred is when moving a chip from an even position to an odd one, or vice-versa. This move always costs exactly 1, regardless of the distance.
Therefore, the problem reduces to deciding whether to move all chips to an even position or an odd position.
- If we gather all chips at an even position, the cost will be the number of chips initially at odd positions.
- If we gather all chips at an odd position, the cost will be the number of chips initially at even positions.
The minimum cost is simply the smaller of these two counts.
Algorithm
- Initialize
evenCount = 0andoddCount = 0. - Iterate through each
posin thepositionarray. - If
posis even, incrementevenCount. - Else (if
posis odd), incrementoddCount. - Return the minimum of
evenCountandoddCount.
Walkthrough
The algorithm is straightforward:
- Count the number of chips located at even positions and the number of chips at odd positions.
- Initialize two counters,
evenCountandoddCount, to zero. - Iterate through the
positionarray once. - For each
posin the array, check its parity.- If
pos % 2 == 0, incrementevenCount. - Otherwise, increment
oddCount.
- If
- After the loop, we have the total counts of chips at even and odd positions.
- The minimum cost to move all chips to the same position is
min(evenCount, oddCount). This is because we can either move all theoddCountchips to an even position (costoddCount) or move all theevenCountchips to an odd position (costevenCount). We choose the cheaper option.
Here is a code snippet for this optimal approach:
class Solution { public int minCostToMoveChips(int[] position) { int evenCount = 0; int oddCount = 0; for (int pos : position) { if (pos % 2 == 0) { evenCount++; } else { oddCount++; } } return Math.min(evenCount, oddCount); }}Complexity
Time
O(N), where N is the number of chips. We only need to iterate through the input array once.
Space
O(1). We only use two integer variables to store the counts.
Trade-offs
Pros
Extremely efficient with linear time complexity.
Simple and elegant solution based on a key insight about the problem's cost structure.
Optimal solution for this problem.
Cons
Requires a small logical leap to understand why only parity matters, which might not be immediately obvious.
Solutions
Solution
class Solution { public int minCostToMoveChips ( int [] position ) { int a = 0 ; for ( int p : position ) { a += p % 2 ; } int b = position . length - a ; return Math . min ( a , b ); } }/** * @param {number[]} position * @return {number} */ var minCostToMoveChips = function ( position ) { let a = 0 ; for ( let v of position ) { a += v % 2 ; } let b = position . length - a ; return Math . min ( a , b ); };class Solution { public: int minCostToMoveChips ( vector < int >& position ) { int a = 0 ; for ( auto & p : position ) a += p & 1 ; int b = position . size () - a ; return min ( a , b ); } };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)Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.