- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

Suppose we have a list containing 0s and 1s, we have to remove values from the front or from the back of the list. Finally, we have to find the minimum number of deletions required such that the remaining list has an equal number of 0s and 1s.

So, if the input is like nums = [1, 1, 1, 0, 0, 1], then the output will be 2, as we can delete the first one 1 and last one 1 so that there's two 1s and two 0s.

To solve this, we will follow these steps −

- longest := 0
- d := a map where put value -1 for key 0
- currSum := 0
- for i in range 0 to size of nums, do
- if nums[i] is same as 0, then
- currSum := currSum - 1

- otherwise,
- currSum := currSum + 1

- if currSum is in d, then
- longest := maximum of longest and i - d[currSum]

- otherwise,
- d[currSum] := i

- if nums[i] is same as 0, then
- return size of nums - longest

Let us see the following implementation to get better understanding −

class Solution: def solve(self, nums): longest = 0 d = {0 : -1} currSum = 0 for i in range(len(nums)): if nums[i] == 0: currSum -= 1 else: currSum += 1 if currSum in d: longest = max(longest, i - d[currSum]) else: d[currSum] = i return len(nums) - longest ob = Solution() nums = [1, 1, 1, 0, 0, 1] print(ob.solve(nums))

[1, 1, 1, 0, 0, 1]

2

- Related Questions & Answers
- Program to find minimum deletions to make string balanced in Python
- Program to find minimum deletions to make strings strings in Python
- Program to find minimum number of operations required to make one number to another in Python
- Find the minimum number of preprocess moves required to make two strings equal in Python
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Minimum number of deletions to make a string palindrome in C++.
- Program to find minimum number of operations required to make one string substring of other in Python
- Program to find minimum number of bricks required to make k towers of same height in Python
- Program to find minimum swaps required to make given anagram in python
- Program to find minimum remove required to make valid parentheses in Python
- Program to count number of minimum swaps required to make it palindrome in Python
- Program to count minimum deletions needed to make character frequencies unique in Python
- Program to count minimum number of operations required to make numbers non coprime in Python?
- Minimum number of given operations required to make two strings equal using C++.
- Program to find minimum number of hops required to reach end position in Python

Advertisements