Find if it is possible to make a binary string which contains given number of “0”, “1” , “01” and “10” as sub sequences
Last Updated :
31 May, 2022
Given four integers l, m, x, and y. The task is to check whether it is possible to make a binary string consisting of l 0’s, m 1’s, x “01” and y “10” as sub-sequences in it.
Examples:
Input: l = 3, m = 2, x = 4, y = 2
Output: Yes
Possible string is “00110”. It contains 3 0’s, 2 1’s,
4 “01” sub-sequences and 2 “10” sub-sequences.
Input: l = 3, m = 2, x = 4, y = 3
Output: No
No such binary string exists.
Approach: The possible string is always of form 00…11…00…. First consists of some number of zeroes, then all ones, and then the remaining number of zeros.
Let l1 be the number of zeros before ones and l2 be the number of zeros after ones then the equations are:
- l1 + l2 = l (Total number of zeros).
- l1 * m = x (Number of “01” sub-sequences).
- m * l2 = y (Number of “10” sub-sequences).
From the above three equations, we get x + y = l * m. If this equation fails for the given values then the string is not possible else print Yes.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible( int l, int m, int x, int y)
{
if (l * m == x + y)
return true ;
return false ;
}
int main()
{
int l = 3, m = 2, x = 4, y = 2;
if (isPossible(l, m, x, y))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class sol
{
static boolean isPossible( int l, int m, int x, int y)
{
if (l * m == x + y)
return true ;
return false ;
}
public static void main(String args[])
{
int l = 3 , m = 2 , x = 4 , y = 2 ;
if (isPossible(l, m, x, y))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def isPossible(l, m, x, y) :
if (l * m = = x + y) :
return True ;
return False ;
if __name__ = = "__main__" :
l = 3 ; m = 2 ; x = 4 ; y = 2 ;
if (isPossible(l, m, x, y)) :
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class sol
{
static Boolean isPossible( int l, int m, int x, int y)
{
if (l * m == x + y)
return true ;
return false ;
}
public static void Main(String []args)
{
int l = 3, m = 2, x = 4, y = 2;
if (isPossible(l, m, x, y))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isPossible(l, m, x, y)
{
if (l * m == x + y)
return true ;
return false ;
}
let l = 3, m = 2, x = 4, y = 2;
if (isPossible(l, m, x, y))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity : O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...