Check if two binary strings can be made equal by swapping 1s occurring before 0s
Last Updated :
26 Oct, 2023
Given two binary strings str1 and str2 having same length, the task is to find if it is possible to make the two binary strings str1 and str2 equal by swapping all 1s occurring at indices less than that of 0s index in the binary string str1.
Examples:
Input: str1 = "0110", str2 = "0011"
Output: Possible
Explanation:
Swapping str1[2] with str1[3] the binary string str1 becomes "0101".
Swapping str1[1] with str1[2] the binary string str1 becomes "0011" .
The binary string str1 becomes equal to the binary string str2 therefore, the required output is Possible.
Input: str1 = "101", str2 = "010"
Output: Not Possible
Approach: The idea is to count the number of 1s and 0s in str1 and str2 and then proceed accordingly. Follow the steps below to solve the problem:
- If the count of 1s and 0s are not equal in str1 and str2, then conversion is not possible.
- Traverse the string.
- Starting from the first character, compare each character one by one. For each different character at i, perform the following steps:
- Check if the current character of the string str1 is '0' and curStr1Ones (stores the current count of 1's of the string str1) is greater than 0. If found to be true, then swap the character with '1' and decrement the value of curStr1Ones by 1.
- Check if the character of the string str1 is '0' and curStr1Ones is equal to 0. If found to be true, then increment the value of the flag by 1 and break the loop.
- Check if the character of the string str1 is '1' and the character of the string str2 is '0'. If found to be true, then swap the character of str1 with '0' and increment the value of curStr1Ones by 1.
- Finally, print "Possible" if the flag is 0, otherwise print "Not Possible".
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if it is possible to make
// two binary strings equal by given operations
void isBinaryStringsEqual(string str1, string str2)
{
// Stores count of 1's and 0's
// of the string str1
int str1Zeros = 0, str1Ones = 0;
// Stores count of 1's and 0's
// of the string str2
int str2Zeros = 0, str2Ones = 0;
int flag = 0;
// Stores current count of 1's
// present in the string str1
int curStr1Ones = 0;
// Count the number of 1's and 0's
// present in the strings str1 and str2
for (int i = 0; i < str1.length(); i++) {
if (str1[i] == '1') {
str1Ones++;
}
else if (str1[i] == '0') {
str1Zeros++;
}
if (str2[i] == '1') {
str2Ones++;
}
else if (str2[i] == '0') {
str2Zeros++;
}
}
// If the number of 1's and 0's
// are not same of the strings str1
// and str2 then print not possible
if (str1Zeros != str2Zeros && str1Ones != str2Ones) {
cout << "Not Possible";
}
else {
// Traversing through the
// strings str1 and str2
for (int i = 0; i < str1.length(); i++) {
// If the str1 character not
// equals to str2 character
if (str1[i] != str2[i]) {
// Swaps 0 with 1 of the
// string str1
if (str1[i] == '0' && curStr1Ones > 0) {
str1[i] = '1';
curStr1Ones--;
}
// Breaks the loop as the count
// of 1's is zero. Hence, no swaps possible
if (str1[i] == '0' && curStr1Ones == 0) {
flag++;
break;
}
// Swaps 1 with 0 in the string str1
if (str1[i] == '1' && str2[i] == '0') {
str1[i] = '0';
curStr1Ones++;
}
}
}
if (flag == 0) {
cout << "Possible";
}
// Print not possible
else {
cout << "Not Possible";
}
}
}
// Driver Code
int main()
{
// Given Strings
string str1 = "0110";
string str2 = "0011";
// Function Call
isBinaryStringsEqual(str1, str2);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG {
// Function to check if it is possible to make
// two binary strings equal by given operations
static void isBinaryStringsEqual(String str1,
String str2)
{
// Stores count of 1's and 0's
// of the string str1
int str1Zeros = 0, str1Ones = 0;
// Stores count of 1's and 0's
// of the string str2
int str2Zeros = 0, str2Ones = 0;
int flag = 0;
// Stores current count of 1's
// present in the string str1
int curStr1Ones = 0;
// Count the number of 1's and 0's
// present in the strings str1 and str2
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == '1')
{
str1Ones++;
}
else if (str1.charAt(i) == '0')
{
str1Zeros++;
}
if (str2.charAt(i) == '1')
{
str2Ones++;
}
else if (str2.charAt(i) == '0')
{
str2Zeros++;
}
}
// If the number of 1's and 0's
// are not same of the strings str1
// and str2 then print not possible
if (str1Zeros != str2Zeros
&& str1Ones != str2Ones)
{
System.out.println("Not Possible");
}
else {
// Traversing through the
// strings str1 and str2
for (int i = 0; i < str1.length(); i++)
{
// If the str1 character not
// equals to str2 character
if (str1.charAt(i) != str2.charAt(i))
{
// Swaps 0 with 1 of the
// string str1
if (str1.charAt(i) == '0'
&& curStr1Ones > 0)
{
str1 = str1.substring(0, i) + '1'
+ str1.substring(i + 1);
curStr1Ones--;
}
// Breaks the loop as the count
// of 1's is zero. Hence, no swaps
// possible
if (str1.charAt(i) == '0'
&& curStr1Ones == 0)
{
flag++;
break;
}
// Swaps 1 with 0 in the string str1
if (str1.charAt(i) == '1'
&& str2.charAt(i) == '0')
{
str1 = str1.substring(0, i) + '0'
+ str1.substring(i+1);
curStr1Ones++;
}
}
}
if (flag == 0) {
System.out.println("Possible");
}
// Print not possible
else {
System.out.println("Not Possible");
}
}
}
// Driver Code
public static void main(String[] args)
{
// Given Strings
String str1 = "0110";
String str2 = "0011";
// Function Call
isBinaryStringsEqual(str1, str2);
}
}
// This code is contributed by dharanendralv23
Python3
# Python program for the above approach
# Function to check if it is possible to make
# two binary strings equal by given operations
def isBinaryStringsEqual(list1, list2) :
str1 = list(list1)
str2 = list(list2)
# Stores count of 1's and 0's
# of the string str1
str1Zeros = 0
str1Ones = 0
# Stores count of 1's and 0's
# of the string str2
str2Zeros = 0
str2Ones = 0
flag = 0
# Stores current count of 1's
# present in the string str1
curStr1Ones = 0
# Count the number of 1's and 0's
# present in the strings str1 and str2
for i in range(len(str1)):
if (str1[i] == '1') :
str1Ones += 1
elif (str1[i] == '0') :
str1Zeros += 1
if (str2[i] == '1') :
str2Ones += 1
elif (str2[i] == '0') :
str2Zeros += 1
# If the number of 1's and 0's
# are not same of the strings str1
# and str2 then print not possible
if (str1Zeros != str2Zeros and str1Ones != str2Ones) :
print("Not Possible")
else :
# Traversing through the
# strings str1 and str2
for i in range(len(str1)):
# If the str1 character not
# equals to str2 character
if (str1[i] != str2[i]) :
# Swaps 0 with 1 of the
# string str1
if (str1[i] == '0' and curStr1Ones > 0) :
str1[i] = '1'
curStr1Ones -= 1
# Breaks the loop as the count
# of 1's is zero. Hence, no swaps possible
if (str1[i] == '0' and curStr1Ones == 0) :
flag += 1
break
# Swaps 1 with 0 in the string str1
if (str1[i] == '1' and str2[i] == '0') :
str1[i] = '0'
curStr1Ones += 1
if (flag == 0) :
print("Possible")
# Print not possible
else :
print("Not Possible")
# Driver Code
# Given Strings
str1 = "0110"
str2 = "0011"
# Function Call
isBinaryStringsEqual(str1, str2)
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
using System.Text;
class GFG
{
// Function to check if it is possible to make
// two binary strings equal by given operations
static void isBinaryStringsEqual(string str1,
string str2)
{
// Stores count of 1's and 0's
// of the string str1
int str1Zeros = 0, str1Ones = 0;
// Stores count of 1's and 0's
// of the string str2
int str2Zeros = 0, str2Ones = 0;
int flag = 0;
// Stores current count of 1's
// present in the string str1
int curStr1Ones = 0;
// Count the number of 1's and 0's
// present in the strings str1 and str2
for (int i = 0; i < str1.Length; i++)
{
if (str1[i] == '1')
{
str1Ones++;
}
else if (str1[i] == '0')
{
str1Zeros++;
}
if (str2[i] == '1')
{
str2Ones++;
}
else if (str2[i] == '0')
{
str2Zeros++;
}
}
// If the number of 1's and 0's
// are not same of the strings str1
// and str2 then print not possible
if (str1Zeros != str2Zeros
&& str1Ones != str2Ones)
{
Console.WriteLine("Not Possible");
}
else
{
// Traversing through the
// strings str1 and str2
for (int i = 0; i < str1.Length; i++)
{
// If the str1 character not
// equals to str2 character
if (str1[i] != str2[i])
{
// Swaps 0 with 1 of the
// string str1
if (str1[i] == '0' && curStr1Ones > 0)
{
StringBuilder sb
= new StringBuilder(str1);
sb[i] = '1';
str1 = sb.ToString();
curStr1Ones--;
}
// Breaks the loop as the count
// of 1's is zero. Hence, no swaps
// possible
if (str1[i] == '0'
&& curStr1Ones == 0)
{
flag++;
break;
}
// Swaps 1 with 0 in the string str1
if (str1[i] == '1' && str2[i] == '0')
{
StringBuilder sb
= new StringBuilder(str1);
sb[i] = '0';
str1 = sb.ToString();
curStr1Ones++;
}
}
}
if (flag == 0)
{
Console.WriteLine("Possible");
}
// Print not possible
else
{
Console.WriteLine("Not Possible");
}
}
}
// Driver Code
static public void Main()
{
// Given Strings
string str1 = "0110";
string str2 = "0011";
// Function Call
isBinaryStringsEqual(str1, str2);
}
}
// This code is contributed by dharanendralv23
JavaScript
<script>
// JavaScript program for the above approach
// Function to check if it is possible to make
// two binary strings equal by given operations
function isBinaryStringsEqual(list1, list2) {
var str1 = list1.split("");
var str2 = list2.split("");
// Stores count of 1's and 0's
// of the string str1
var str1Zeros = 0,
str1Ones = 0;
// Stores count of 1's and 0's
// of the string str2
var str2Zeros = 0,
str2Ones = 0;
var flag = 0;
// Stores current count of 1's
// present in the string str1
var curStr1Ones = 0;
// Count the number of 1's and 0's
// present in the strings str1 and str2
for (var i = 0; i < str1.length; i++) {
if (str1[i] === "1") {
str1Ones++;
} else if (str1[i] === "0") {
str1Zeros++;
}
if (str2[i] === "1") {
str2Ones++;
} else if (str2[i] === "0") {
str2Zeros++;
}
}
// If the number of 1's and 0's
// are not same of the strings str1
// and str2 then print not possible
if (str1Zeros !== str2Zeros && str1Ones !== str2Ones) {
document.write("Not Possible");
} else {
// Traversing through the
// strings str1 and str2
for (var i = 0; i < str1.length; i++) {
// If the str1 character not
// equals to str2 character
if (str1[i] !== str2[i]) {
// Swaps 0 with 1 of the
// string str1
if (str1[i] === "0" && curStr1Ones > 0) {
str1[i] = "1";
curStr1Ones--;
}
// Breaks the loop as the count
// of 1's is zero. Hence, no swaps
// possible
if (str1[i] === "0" && curStr1Ones === 0) {
flag++;
break;
}
// Swaps 1 with 0 in the string str1
if (str1[i] === "1" && str2[i] === "0") {
str1[i] = "0";
curStr1Ones++;
}
}
}
if (flag === 0) {
document.write("Possible");
}
// Print not possible
else {
document.write("Not Possible");
}
}
}
// Driver Code
// Given Strings
var str1 = "0110";
var str2 = "0011";
// Function Call
isBinaryStringsEqual(str1, str2);
</script>
Time Complexity: O(|str1|), where |str1| is the length of the input string. This is because the program loops through the strings once to count the number of ones and zeros, and then loops through the strings again to perform the swaps. The inner loop has a constant time complexity, so the overall time complexity is linear.
Auxiliary Space: O(1), The space complexity of the program is O(1), as it only uses a constant amount of extra space to store the counts and the flag variable. The input strings are not modified and do not take extra space as they are passed by value.
Another Approach:
- Define a function named "areBinaryStringsEqual" that takes two string arguments: str1 and str2.
- Initialize two integer variables ones1 and ones2 to count the number of 1s in both strings.
- Traverse both strings using a for loop and count the number of 1s in each string.
- If the number of 1s is not the same in both strings, return false.
- Initialize a variable count to keep track of the number of 0s that need to be swapped in string 1.
- Traverse both strings using a for loop and check if they can be made equal by swapping 1s and 0s.
- If the characters at the same position in both strings are not equal, check the following:
a. If the character in string 1 is 1 and in string 2 is 0, increment the count.
b. If the character in string 1 is 0 and count is greater than 0, decrement the count.
c. If the characters cannot be made equal by swapping, return false. - If the loop completes without returning false, the strings can be made equal by swapping 1s and 0s. Return true.
- In the main function, input two binary strings str1 and str2.
- Check if the strings can be made equal by calling the "areBinaryStringsEqual" function.
- If the function returns true, print "Possible". Otherwise, print "Not Possible".
- Return 0 to end the program.
Below is the implementation of the above approach:
C++
// Include necessary header files
#include <iostream>
#include <string>
using namespace std;
// Function to check if two binary strings can be made equal by swapping 1s and 0s
bool areBinaryStringsEqual(string str1, string str2) {
// Count number of 1s in both strings
int ones1 = 0, ones2 = 0;
for (int i = 0; i < str1.length(); i++) {
if (str1[i] == '1') ones1++;
if (str2[i] == '1') ones2++;
}
// If the number of 1s is not the same in both strings, return false
if (ones1 != ones2) return false;
// Count variable to keep track of number of 0s that need to be swapped in string 1
int count = 0;
// Traverse both strings and check if they can be made equal by swapping 1s and 0s
for (int i = 0; i < str1.length(); i++) {
// If the characters at the same position in both strings are not equal
if (str1[i] != str2[i]) {
// If the character in string 1 is 1 and in string 2 is 0, increment the count
if (str1[i] == '1' && str2[i] == '0') count++;
// If the character in string 1 is 0 and count is greater than 0, decrement the count
else if (str1[i] == '0' && count > 0) count--;
// If the characters cannot be made equal by swapping, return false
else return false;
}
}
// If the loop completes without returning false, the strings can be made equal by swapping 1s and 0s
return true;
}
// Driver code
int main() {
// Input binary strings
string str1 = "0110";
string str2 = "0011";
// Check if the strings can be made equal and print output accordingly
if (areBinaryStringsEqual(str1, str2)) {
cout << "Possible";
} else {
cout << "Not Possible";
}
// Return 0 to end the program
return 0;
}
//This code is contributed by rudra1807raj
Java
public class Main {
// Function to check if two binary
// strings can be made equal by swapping 1s and 0s
public static boolean areBinaryStringsEqual(String str1, String str2) {
// Count number of 1s in both strings
int ones1 = 0, ones2 = 0;
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) == '1') ones1++;
if (str2.charAt(i) == '1') ones2++;
}
// If the number of 1s is not the same in both strings, return false
if (ones1 != ones2) return false;
// Count variable to keep track of
// number of 0s that need to be swapped in string 1
int count = 0;
// Traverse both strings and check if
// they can be made equal by swapping 1s and 0s
for (int i = 0; i < str1.length(); i++) {
// If the characters at the same position
// in both strings are not equal
if (str1.charAt(i) != str2.charAt(i)) {
// If the character in string 1
// is 1 and in string 2 is 0, increment the count
if (str1.charAt(i) == '1' && str2.charAt(i) == '0') count++;
// If the character in string 1 is 0
// and count is greater than 0, decrement the count
else if (str1.charAt(i) == '0' && count > 0) count--;
// If the characters cannot be made equal by swapping, return false
else return false;
}
}
// If the loop completes without returning false,
// the strings can be made equal by swapping 1s and 0s
return true;
}
// Driver code
public static void main(String[] args) {
// Input binary strings
String str1 = "0110";
String str2 = "0011";
// Check if the strings can be
// made equal and print output accordingly
if (areBinaryStringsEqual(str1, str2)) {
System.out.println("Possible");
} else {
System.out.println("Not Possible");
}
}
}
Python3
# Function to check if two binary strings can be made equal by swapping 1s and 0s
def are_binary_strings_equal(str1, str2):
# Count the number of 1s in both strings
ones1 = 0
ones2 = 0
for i in range(len(str1)):
if str1[i] == '1':
ones1 += 1
if str2[i] == '1':
ones2 += 1
# If the number of 1s is not the same in both strings, return False
if ones1 != ones2:
return False
# Count variable to keep track of the number of 0s that need to be swapped in string 1
count = 0
# Traverse both strings and check if they can be made equal by swapping 1s and 0s
for i in range(len(str1)):
# If the characters at the same position in both strings are not equal
if str1[i] != str2[i]:
# If the character in string 1 is '1' and in string 2 is '0', increment the count
if str1[i] == '1' and str2[i] == '0':
count += 1
# If the character in string 1 is '0' and count is greater than 0, decrement the count
elif str1[i] == '0' and count > 0:
count -= 1
# If the characters cannot be made equal by swapping, return False
else:
return False
# If the loop completes without returning False, the strings can be made equal by swapping 1s and 0s
return True
# Driver code
if __name__ == "__main__":
# Input binary strings
str1 = "0110"
str2 = "0011"
# Check if the strings can be made equal and print output accordingly
if are_binary_strings_equal(str1, str2):
print("Possible")
else:
print("Not Possible")
# This code is contributed by akshitaguprzj3
C#
using System;
class Program
{
// Function to check if two binary strings can be made equal by swapping 1s and 0s
static bool AreBinaryStringsEqual(string str1, string str2)
{
// Count the number of 1s in both strings
int ones1 = 0, ones2 = 0;
for (int i = 0; i < str1.Length; i++)
{
if (str1[i] == '1') ones1++;
if (str2[i] == '1') ones2++;
}
// If the number of 1s is not the same in both strings, return false
if (ones1 != ones2) return false;
// Count variable to keep track of the number of 0s that need to be swapped in string 1
int count = 0;
// Traverse both strings and check if they can be made equal by swapping 1s and 0s
for (int i = 0; i < str1.Length; i++)
{
// If the characters at the same position in both strings are not equal
if (str1[i] != str2[i])
{
// If the character in string 1 is '1' and in string 2 is '0', increment the count
if (str1[i] == '1' && str2[i] == '0') count++;
// If the character in string 1 is '0' and count is greater than 0, decrement the count
else if (str1[i] == '0' && count > 0) count--;
// If the characters cannot be made equal by swapping, return false
else return false;
}
}
// If the loop completes without returning false, the strings can be made equal by swapping 1s and 0s
return true;
}
// Main method
static void Main()
{
// Input binary strings
string str1 = "0110";
string str2 = "0011";
// Check if the strings can be made equal and print output accordingly
if (AreBinaryStringsEqual(str1, str2))
{
Console.WriteLine("Possible");
}
else
{
Console.WriteLine("Not Possible");
}
}
}
JavaScript
// Function to check if two binary strings can be made equal by swapping 1s and 0s
function areBinaryStringsEqual(str1, str2) {
// Count number of 1s in both strings
let ones1 = 0, ones2 = 0;
for (let i = 0; i < str1.length; i++) {
if (str1[i] === '1') ones1++;
if (str2[i] === '1') ones2++;
}
// If the number of 1s is not the same in both strings, return false
if (ones1 !== ones2) return false;
// Count variable to keep track of the number of 0s that need to be swapped in string 1
let count = 0;
// Traverse both strings and check if they can be made equal by swapping 1s and 0s
for (let i = 0; i < str1.length; i++) {
// If the characters at the same position in both strings are not equal
if (str1[i] !== str2[i]) {
// If the character in string 1 is 1 and in string 2 is 0, increment the count
if (str1[i] === '1' && str2[i] === '0') count++;
// If the character in string 1 is 0 and count is greater than 0, decrement the count
else if (str1[i] === '0' && count > 0) count--;
// If the characters cannot be made equal by swapping, return false
else return false;
}
}
// If the loop completes without returning false, the strings can
// be made equal by swapping 1s and 0s
return true;
}
// Driver code
const str1 = "0110";
const str2 = "0011";
// Check if the strings can be made equal and print output accordingly
if (areBinaryStringsEqual(str1, str2)) {
console.log("Possible");
} else {
console.log("Not Possible");
}
Time complexity: The code traverses each character of the input strings twice, so the time complexity is O(n), where n is the length of the strings.
Auxiliary Space: The code uses a constant amount of extra space, so the space complexity is O(1).
Similar Reads
Check if two binary strings can be made equal by swapping pairs of unequal characters
Given two binary strings S1 and S2 of length N (1 ? N ? 105), the task is to check if it is possible to convert the string S1 to S2 by performing the following operations any number of times: Select any two indices i and j (1 ? i < j ? N) such that S1[i] is â0â and S1[j] is â1â.Swap S1[i] with S1
12 min read
Check if two strings can be made equal by swapping pairs of adjacent characters
Given two strings A and B of length N and M respectively and an array arr[] consisting of K integers, the task is to check if the string B can be obtained from the string A by swapping any pair of adjacent characters of the string A any number of times such that the swapped indices are not present i
15+ min read
Check if two array of string are equal by performing swapping operations
Given two arrays arr[] and brr[] of the same size containing strings of equal lengths. In one operation any two characters from any string in brr[] can be swapped with each other or swap any two strings in brr[]. The task is to find whether brr[] can be made equal to arr[] or not. Example: Input: ar
8 min read
Check if a string can be made equal to another string by swapping or replacement of characters
Given two strings S1 and S2, the task is to check if string S1 can be made equal to string S2 by swapping any pair of characters replacing any character in the string S1. If it is possible to make the string S1 equal to S2, then print "Yes". Otherwise, print "No". Examples: Input: S1 = âabcâ, S2 = â
8 min read
Check if two strings can be made equal by swapping one character among each other
Given two strings A and B of length N, the task is to check whether the two strings can be made equal by swapping any character of A with any other character of B only once.Examples: Input: A = "SEEKSFORGEEKS", B = "GEEKSFORGEEKG" Output: Yes "SEEKSFORGEEKS" and "GEEKSFORGEEKG" After removing the el
10 min read
Check if two Binary Strings can be made equal by doing bitwise XOR of adjacent
Given binary strings S1 and S2 of length N, the task is to check if S2 can be made equal to S1 by performing the following operations on S2: The first operation is Si = Si ? Si+1. ( ? is the XOR operation)The second operation is Si+1 = Si+1 ? Si. Examples: Input: S1 = "00100", S2 = "00011" Output: Y
6 min read
Check if two strings can be made equal by reversing a substring of one of the strings
Given two strings X and Y of length N, the task is to check if both the strings can be made equal by reversing any substring of X exactly once. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: X = "adcbef", Y = "abcdef"Output: YesExplanation: Strings can be made equal by
12 min read
Check if count of 1s can be made greater in a Binary string by changing 0s adjacent to 1s
Given a binary string S of size N, the task is to check if the count of 1s can be made greater than the count of 0s by changing the 0s adjacent to 1s to any other characters. If it is possible, then print Yes. Otherwise, print No. Note: Any index having 1 can be chosen at most once. Examples: Input:
9 min read
Check if two non-duplicate strings can be made equal after at most two swaps in one string
Given two strings A and B consisting of unique lowercase letters, the task is to check if both these strings can be made equal by using at most two swaps. Print Yes if they can. Otherwise, print No. Example: Input: A="abcd", B="badc"Output: YesFirst swap a and b, and then swap c and d, in string A.I
15+ min read
Make given Binary Strings equal by replacing two consecutive 0s with single 1 repeatedly
Given two binary strings str1 and str2, the task is to check whether it is possible to convert str1 to str2 by combining two consecutive 0's into a single 1 repeatedly. Examples: Input: str1 = "00100", str2 = "111" Output: Yes Explanation: Combine first two zeros to one and combine last two zeros to
6 min read