Check if a Binary String contains A pairs of 0s and B independent 0s or not
Given a binary string S and two positive integers A and B, the task is to check if the string consists of A independent pair of adjacent 0s and B independent number of 0s in the binary string or not. If found to be true, then print “Yes”. Otherwise, print “No”.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: S = “10100”, A = 1, B = 1
The given string consists of A (=1) pairs of adjacent 0s and B (=1) independent number of 0s.
Input: S = “0101010”, A = 1, B = 2
The given string has no pair of adjacent 0s.
Approach: Follow the steps below to solve the problem:
- Traverse the given string S using a variable, say i, and perform the following steps:
- If the current character is ‘0’ and its adjacent character is ‘0’ and A is at least 1, then decrease A by 1 and increase the pointer i by 1.
- Otherwise, if the current character is ‘0’ and B is at least 1, then decrease B by 1.
- After completing the above steps, if the value of A and B is 0, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)