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.
1import java.util.List;
2
3public class Solution {
4 public int minCostToMoveChips(List<Integer> position) {
5 int oddCount = 0, evenCount = 0;
6 for (int pos : position) {
7 if (pos % 2 == 0) evenCount++;
8 else oddCount++;
9 }
10 return Math.min(oddCount, evenCount);
11 }
12
13 public static void main(String[] args) {
14 Solution sol = new Solution();
15 System.out.println(sol.minCostToMoveChips(Arrays.asList(1, 2, 3)));
16 }
17}
The Java solution uses a List to hold chip positions. It counts chips in odd and even positions, then returns the least of the two counts using Math.min. This efficiently computes 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.
1def minCostToMoveChips(position):
2 count = [0, 0]
3 for p in position:
4 count[p % 2] += 1
5 return min(count)
6
7# Example usage
8position = [1, 2, 3]
9print(minCostToMoveChips(position))
Using a simple list to keep the even and odd counts seeks an effective way to track and compute the minimal movement cost across chip positions.