The main observation here is that moving chips from position p to p+2 or p-2 incurs no cost. Hence, the cost to align all chips into one position is essentially the cost of moving all odd-indexed chips to even positions or vice versa.
To achieve this, count the number of chips at odd positions and the number of chips at even positions. The minimum cost to move all chips to the same position is the lesser of the two counts.
Time Complexity: O(n), where n is the number of chips.
Space Complexity: O(1) because only a fixed amount of extra space is used.
1def minCostToMoveChips(position):
2 odd_count = sum(1 for p in position if p % 2 == 1)
3 even_count = len(position) - odd_count
4 return min(odd_count, even_count)
5
6# Example usage
7position = [1, 2, 3]
8print(minCostToMoveChips(position))
The Python solution uses list comprehensions to count chips at odd positions. Then it directly calculates chips at even positions as the complement and returns the minimum cost.
A similar but slightly varied approach leverages modular arithmetic to classify indices. As the cost is incurred when moving by an odd number of steps, the strategy remains to count parity of indices and work from there.
Time Complexity: O(n) for iterating through the list of positions.
Space Complexity: O(1), with fixed space used to track counts.
1#include <stdio.h>
2
3int minCostToMoveChips(int* position, int positionSize) {
4 int count[2] = {0};
5 for (int i = 0; i < positionSize; i++) {
6 count[position[i] % 2]++;
7 }
8 return count[0] < count[1] ? count[0] : count[1];
9}
10
11int main() {
12 int position[] = {1, 2, 3};
13 int size = sizeof(position) / sizeof(position[0]);
14 printf("%d\n", minCostToMoveChips(position, size));
15 return 0;
16}
By using an array `count` to track counts of even and odd indices, this solution provides an efficient way to determine the minimum movement cost using basic arithmetic for index parity.