VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-deletions-in-a-binary-string-to-remove-all-subsequences-of-the-form-0101/

⇱ Minimize deletions in a Binary String to remove all subsequences of the form "0101" - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize deletions in a Binary String to remove all subsequences of the form "0101"

Last Updated : 5 Jul, 2021

Given a binary string S of length N, the task is to find the minimum number of characters required to be deleted from the string such that no subsequence of the form “0101” exists in the string.

Examples:

Input: S = "0101101"
Output: 2
Explanation: Removing S[1] and S[5] modifies the string to 00111. Therefore, no subsequence of the type 0101 can be obtained from the given string.

Input: S = "0110100110"
Output: 2

Approach: Follow the steps below to solve the problem:

  • The required valid string can consist of at most three blocks of the same elements i.e. the strings can be one of the following patterns "00...0", "11...1", "00...01...1", "1...10..0", "00..01...10..0", "1...10...01...1".
  • Count frequencies of 0s and 1s of a block using partial sum.
  • Fix the starting and ending indices of blocks of 0s and 1s and determine the minimum number of characters required to be deleted by the calculated partial sums.
  • Therefore, check the length of the longest string that can be obtained by removing the subsequences of the given type.

Below is the implementation of the above approach: 
 


Output: 
3

 

Time Complexity: O(N2)
Auxiliary Space: O(N)

Comment