Minimum Cost to Move Chips to The Same Position - Problem

We have n chips, where the position of the i-th 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 i-th chip from position[i] to:

  • position[i] + 2 or position[i] - 2 with cost = 0
  • position[i] + 1 or position[i] - 1 with cost = 1

Return the minimum cost needed to move all the chips to the same position.

Input & Output

Example 1 — Mixed Positions
$ Input: position = [1,2,3]
Output: 1
💡 Note: Odd positions: 1,3 (count=2). Even positions: 2 (count=1). Move 1 chip from even to odd or vice versa, cost = min(2,1) = 1.
Example 2 — Same Parity
$ Input: position = [2,2,2,3,3]
Output: 2
💡 Note: Even positions: 2,2,2 (count=3). Odd positions: 3,3 (count=2). Move 2 chips from odd to even positions, cost = min(3,2) = 2.
Example 3 — All Same Position
$ Input: position = [1,1000000000]
Output: 1
💡 Note: One odd (1), one even (1000000000). Need to move 1 chip to change its parity, cost = min(1,1) = 1.

Constraints

  • 1 ≤ position.length ≤ 100
  • 1 ≤ position[i] ≤ 109

Visualization

Tap to expand
Chip Movement: Understanding Cost StructureInput: [1,2,3]123Odd: Red, Even: GreenMovement Rules:±2 positions = Cost 0±1 position = Cost 1Optimal Strategy:Count: 2 odd positions, 1 even positionMove 1 chip from even to odd (or vice versa)Minimum Cost = min(2, 1) = 1
Understanding the Visualization
1
Input
Chips at various positions [1,2,3]
2
Movement Rules
±2 costs 0 (preserves parity), ±1 costs 1 (changes parity)
3
Strategy
Move minority parity group to majority group
Key Takeaway
🎯 Key Insight: Only parity matters - count chips at even vs odd positions and move the smaller group
Asked in
Google 15 Amazon 12 Facebook 8
25.0K Views
Medium Frequency
~10 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen