Minimize count of alternating subsequences to divide given Binary String with subsequence number
Given a binary string S of length N. The task is to find the following:
- The minimum number of subsequences, string S can be divided into, such that the subsequence does not contain adjacent zeroes or ones.
- Subsequence number to which each character of string S belongs.
If there are many answers, output any.
Input: S = “0011”, N = 4
1 2 2 1
There can be a minimum of 2 subsequences such that they donot have any adjacent zeroes or ones.
Subsequence 1: “01”
Subsequence 2: “01”
Also, the first character of S(‘0’) belongs to subsequence 1(“01”)
Second character of S(‘0’) belongs to subsequence 2(“01”)
Third character of S(‘1’) belongs to subsequence 2(“01”)
Fourth character of S(‘1’) belongs to subsequence 1(“01”)
Input: S = “1000110”, N = 7
1 1 2 3 3 2 2
Approach: It is to be noted that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. Now, follow the steps below to solve the problem:
- Create a vector ans to store the subsequences to which each character of string S belongs.
- Also, create two vectors endZero and endOne to store the subsequences ending with ‘0’ and ‘1’ respectively.
- As there can’t be adjacent zeroes or ones in a subsequence. Hence, if a character is ‘0’, the next character to be put in the subsequence must be ‘1’ and vice versa.
- Now, using a loop traverse over each character of S and check if it is ‘0’ or ‘1’. Also, declare a variable newSeq which represents the new subsequence to be formed if consecutive zeroes or ones are encountered.
- If a character is ‘0’, check whether the vector endOne is empty or not:
- If it is empty, then push newSeq into endZero.
- Otherwise, put the last subsequence of endOne into newSeq. Now, this last subsequence of endOne does not end with ‘1’ anymore as ‘0’ has been appended to it. Thus, push it in endZero.
- Similarly, if a character in S is ‘1’, the same steps as above are followed, i.e., check whether vector endZero is empty or not:
- If it is empty, then push newSeq into endOne.
- Otherwise, put the last subsequence of endZero into newSeq. Now, this last subsequence of endZero does not end with ‘0’ anymore as ‘1’ has been appended to it. Thus, push it in endOne.
- Then, push newSeq into vector ans.
- Repeat the above steps for each character of S.
- The minimum number of subsequences will be given by the sum of the sizes of endZero and endOne.
- Finally, output the minimum number of subsequences and the vector ans.
Below is the implementation of the above approach:
3 1 1 2 3 3 2 2
Time Complexity: O(N)
Auxiliary Space: O(N)