#1217
Minimum Cost to Move Chips to The Same Position
EasyArrayMathGreedyGreedyCounting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the fact that chips can move between even positions at no cost and odd positions at no cost. Thus, we only need to count how many chips are on even and odd positions and move the smaller group to minimize the cost.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two counters for even and odd positioned chips.
- 2Step 2: Iterate through the position array and increment the respective counter based on whether the position is even or odd.
- 3Step 3: The minimum cost will be the smaller of the two counters (either move all odd chips to even or all even chips to odd).
- 4Step 4: Return the minimum cost.
solution.py4 lines
1def minCostToMoveChips(position):
2 even_count = sum(1 for pos in position if pos % 2 == 0)
3 odd_count = len(position) - even_count
4 return min(even_count, odd_count)ℹ
Complexity note: The time complexity is O(n) as we only traverse the list once to count even and odd chips. The space complexity is O(1) since we only use a fixed number of variables.
- 1Chips can move between even positions at no cost, and between odd positions at no cost.
- 2The minimum cost to align all chips is determined by the smaller group (even or odd).
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.