[Python3] 1-pass O(N)
Algo\nThis implementation is similar to the popular threads in Discuss. But here we built the locations of 1s on-the-fly. \n\nImplementation - simulation \n\ncl
**Algo**\nThis implementation is similar to the popular threads in Discuss. But here we built the locations of 1s on-the-fly. \n\n**Implementation** - simulation \n```\nclass Solution:\n    def minMoves(self, nums: List[int], k: int) -> int:\n        ii = val = 0 \n        ans = inf\n        loc = [] # location of 1s\n        for i, x in enumerate(nums): \n            if x: \n                loc.append(i)\n                m = (ii + len(loc) - 1)//2 # median \n                val += loc[-1] - loc[m] - (len(loc)-ii)//2 # adding right \n                if len(loc) - ii > k: \n                    m = (ii + len(loc))//2 # updated median \n                    val -= loc[m] - loc[ii] - (len(loc)-ii)//2 # removing left \n                    ii += 1\n                if len(loc)-ii == k: ans = min(ans, val) # len(ones) - ii effective length\n        return ans \n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`\n\nA shorter solution given by @lee215 is in this [post](https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/discuss/987347/JavaC%2B%2BPython-Solution).\n```\nclass Solution:\n    def minMoves(self, nums: List[int], k: int) -> int:\n        loc = [i for i, x in enumerate(nums) if x]\n        prefix = [0]\n        for x in loc: prefix.append(prefix[-1] + x)\n        \n        ans = inf\n        for i in range(len(loc)-k+1): \n            ans = min(ans, (prefix[i+k] - prefix[i+(k+1)//2]) - (prefix[i+k//2] - prefix[i]))\n        return ans - (k//2)*((k+1)//2)\n```
['Python3']