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.

Algorithm

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

How It Works

The algorithm uses a cumulative sum approach where we treat 0s as -1 and 1s as +1. When the cumulative sum is the same at two different positions, the subarray between them has equal 0s and 1s. We track the longest such balanced subarray and subtract its length from the total to get minimum deletions.

Example

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

The output of the above code is −

2

Step-by-Step Execution

For nums = [1, 1, 1, 0, 0, 1] −

nums = [1, 1, 1, 0, 0, 1]
# i=0: currSum=1, d={0:-1, 1:0}
# i=1: currSum=2, d={0:-1, 1:0, 2:1}
# i=2: currSum=3, d={0:-1, 1:0, 2:1, 3:2}
# i=3: currSum=2, found in d, longest = max(0, 3-1) = 2
# i=4: currSum=1, found in d, longest = max(2, 4-0) = 4
# i=5: currSum=2, found in d, longest = max(4, 5-1) = 4

print("Longest balanced subarray:", 4)
print("Minimum deletions:", 6 - 4)

The output of the above code is −

Longest balanced subarray: 4
Minimum deletions: 2

Conclusion

This algorithm efficiently finds the minimum deletions by identifying the longest balanced subarray using cumulative sum mapping. The time complexity is O(n) and space complexity is O(n) for the dictionary storage.

Updated on: 2026-03-25T11:26:13+05:30

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements