Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find minimum adjacent swaps for K consecutive ones in Python
Suppose we have one binary array nums, and a value k. In one move, we can select two adjacent indices and swap their values. We have to find the minimum number of moves required so that nums has k consecutive 1's.
So, if the input is like nums = [1,0,0,1,0,1,0,1], k = 3, then the output will be 2 because in one swap we can make array from [1,0,0,1,0,1,0,1] to [1,0,0,0,1,1,0,1], then [1,0,0,0,1,1,1,0].
To solve this, we will follow these steps −
j := 0
val := 0
ans := 999999
loc := a new list
-
for each index i, and value x in nums, do
-
if x is non-zero, then
insert i at the end of loc
m := quotient of (j + size of loc - 1) /2
val := val + loc[-1] - loc[m] - quotient of (size of loc -j)/2
-
if length of loc - j > k, then
m := quotient of (j + size of loc) /2
val := val - loc[m] - loc[j] - quotient of (size of loc -j)/2
j := j + 1
-
if size of loc -j is same as k, then
ans := minimum of ans and val
-
return ans
Example
Let us see the following implementation to get better understanding
def solve(nums, k):
j = val = 0
ans = 999999
loc = []
for i, x in enumerate(nums):
if x:
loc.append(i)
m = (j + len(loc) - 1)//2
val += loc[-1] - loc[m] - (len(loc)-j)//2
if len(loc) - j > k:
m = (j + len(loc))//2
val -= loc[m] - loc[j] - (len(loc)-j)//2
j += 1
if len(loc)-j == k:
ans = min(ans, val)
return ans
nums = [1,0,0,1,0,1,0,1]
k = 3
print(solve(nums, k))
Input
[1,0,0,1,0,1,0,1], 3
Output
2