VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-it-is-possible-to-convert-binary-string-into-unary-string/

⇱ Check If it is Possible to Convert Binary String into Unary String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check If it is Possible to Convert Binary String into Unary String

Last Updated : 11 Dec, 2023

Given a binary string S of length N. You can apply following operation on S any number of times. Choose two adjacent characters, such that both are 1's or 0's. Then invert them, Formally, if both are 0's then into 1's or vice-versa. Then your task is to output YES or NO, by checking that using given operations, Is it possible to convert S into either all 0's or 1's ?

Examples:

Input: N = 6, S = "110110"
Output: YES
Explanation: The operations are performed as:

  • First operation: S1 = 1 and S2 = 1. Both are same, therefore invert them. Then updated S = 000110
  • Second operation: S4 = 1 and S5 = 1. Both are same, therefore invert them. Then updated S = 000000

All the string is converted into 0s. Therefore, output is YES. Note that S also can be converted into all 1s by following the sequence: 110110 → 110000 → 110011 → 111111. Both conversions are valid.

Input: N = 7, S = 0101010
Output: NO
Explanation: It can be verified that S can't be converted into all 1s or 0s by using give operation.

Approach: To Solve this problem follow the below idea

It's an observation-based problem. It must be observed that, All occurrence of either number (zero or one) must be existed in pair in order to change the entire S to 1 or 0. Let us take some examples:

  • 001100 = Possible as both 0 and 1 are occurred in pair.
  • 00100 = Possible because 0 occurred in pair.
  • 00101 = Not possible as none of the element occurred in pair.
  • 1100111 = Possible as 0 occurred in pair

Now, we can use Stack to solve this problem:

  • First, we have to create a Stack.
  • Iterate on String and follow below steps:
    • If stack is empty or peek and current characters are different then put current character into Stack
    • Else If current character and peek character of Stack is same, then pop out the peek element from stack.
  • If number of elements in stack is either 0 or 1, Then output YES, else NO.

Steps were taken to solve the problem:

  • Create a Stack of Character data type let say Stk.
  • Iterate over each character of S using loop and follow below mentioned steps under the scope of loop:
    • If (Stk is not empty && Peek character == current character)
      • Pop out the peek character from Stk
    • Else
      • Insert character into Stk
  • If (Size of Stk is less than or equal to 1)
    • Output YES
  • Else
    • Output NO

Below is the code to implement the approach:


Output
YES

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

Comment