
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
Count Minimum K-Length Sublist to Make All Items Zero in Python
Suppose we have a list of numbers called nums that stored 0s and 1s. We have another value k.
Now consider there is an operation where we flip a sublist of length k such that all 1s will be 0s and all 0s will be 1s. We have to find the minimum number of operations required to change nums into all 1s to 0s. If we cannot change it return -1.
So, if the input is like nums = [1,1,1,0,0,1,1,1], k = 3, then the output will be 2, as we can flip the first three numbers to zero and then flip the last three numbers to zero.
To solve this, we will follow these steps −
n := size of nums
res := 0, flipped := 0
to_conv := a list of size n and fill with 0
-
for i in range 0 to n, do
flipped := flipped XOR to_conv[i]
cur := nums[i]
cur := cur XOR flipped
-
if cur is same as 1, then
flipped := flipped XOR 1
res := res + 1
-
if i + k - 1 >= n, then
return -1
-
if i + k < n, then
to_conv[i + k] := 1
return res
Example
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums, k): n = len(nums) res = 0 flipped = 0 to_conv = [0] * n for i in range(n): flipped ^= to_conv[i] cur = nums[i] cur ^= flipped if cur == 1: flipped ^= 1 res += 1 if i + k - 1 >= n: return -1 if i + k < n: to_conv[i + k] = 1 return res ob = Solution() nums = [1,1,1,0,0,1,1,1] k = 3 print(ob.solve(nums, k))
Input
[1,1,1,0,0,1,1,1], 3
Output
2