Program to find minimum number of deletions required from two ends to make list balanced in Python

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
• return size of nums - longest

Let us see the following implementation to get better understanding −

Example

Live Demo

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))

Input

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

Output

2

Updated on: 19-Oct-2020

117 Views

Kickstart Your Career

Get certified by completing the course

Advertisements