VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-binary-string-alternate-x-y-occurrences/

⇱ Rearrange a binary string as alternate x and y occurrences - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rearrange a binary string as alternate x and y occurrences

Last Updated : 20 Jul, 2022

Given a binary string s and two integers x and y are given. Task is to arrange the given string in such a way so that '0' comes X-time then '1' comes Y-time and so on until one of the '0' or '1' is finished. Then concatenate rest of the string and print the final string. 
Given : x or y can not be 0

Examples: 

Input : s = "0011"
 x = 1
 y = 1
Output : 0101
x is 1 and y is 1. So first we print
'0' one time the '1' one time and 
then we print '0', after printing '0',
all 0's are vanished from the given
string so we concatenate rest of the 
string which is '1'. 

Input : s = '1011011'
 x = 1
 y = 1
Output : 0101111
  1. Count number of 0's and 1's in the string. 
  2. Run a loop until either one of the alphabets is finished. 
    1. First print '0' upto x and decrement count of 0. 
    2. Then print '1' upto y and decrement count of 1.  

Implementation:


Output
01101101101101101000000

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

Comment
Article Tags: