💡Swift - Optimal Solution - Sliding Window
SolutionComplexity
Time:O(n)
Space:O(n)
# Solution
```
class Solution {
    func minMoves(_ nums: [Int], _ k: Int) -> Int {
        // Collect indices where the value is 1.
        let onePositions = nums.enumerated().compactMap { $1 == 1 ? $0 : nil }
        let totalOnes = onePositions.count
        
        // Compute offsets to simplify cost calculation.
        let offsets = onePositions.enumerated().map { $1 - $0 }
        
        // Determine the initial median index in the sliding window.
        var windowMid = (k - 1) / 2
        let sizeLeft = windowMid
        let sizeRight = k - 1 - sizeLeft
        
        // Compute initial left and right costs.
        var leftCost = (0..<windowMid).reduce(0) { $0 + (offsets[windowMid] - offsets[$1]) }
        var rightCost = ((windowMid + 1)..<k).reduce(0) { $0 + (offsets[$1] - offsets[windowMid]) }
        var minCost = leftCost + rightCost
        
        // Slide the window across offsets.
        for nextWindowMid in (windowMid + 1)..<(totalOnes - sizeRight) {
            let midDiff = offsets[nextWindowMid] - offsets[windowMid]
            leftCost -= offsets[windowMid] - offsets[windowMid - sizeLeft]
            leftCost += midDiff * sizeLeft
            rightCost -= midDiff * sizeRight
            rightCost += offsets[nextWindowMid + sizeRight] - offsets[nextWindowMid]
            
            minCost = min(minCost, leftCost + rightCost)
            windowMid = nextWindowMid  // Update the median index.
        }
        
        return minCost
    }
}
```
# Complexity
- Time: $$O(n)$$
- Space: $$O(n)$$
['Swift', 'Sliding Window', 'Prefix Sum']