Given a binary string, find if it is possible to make all its digits equal (either all 0’s or all 1’s) by flipping exactly one bit.
Input: 101
Output: Yes
Explanation: In 101, the 0 can be flipped
to make it all 1
Input: 11
Output: No
Explanation: No matter whichever digit you
flip, you will not get the desired string.
Input: 1
Output: Yes
Explanation: We can flip 1, to make all 0's
Method 1 (Counting 0’s and 1’s)
If all digits of a string can be made identical by doing exactly one flip, that means the string has all its digits equal to one another except this digit which has to be flipped, and this digit must be different than all other digits of the string. The value of this digit could be either zero or one. Hence, this string will either have exactly one digit equal to zero, and all other digits equal to one, or exactly one digit equal to one, and all other digit equal to zero.
Therefore, we only need to check whether the string has exactly one digit equal to zero/one, and if so, the answer is yes; otherwise the answer is no.
Below is the implementation of above idea.
C++
#include <bits/stdc++.h>
using namespace std;
bool canMakeAllSame(string str)
{
int zeros = 0, ones = 0;
for ( char ch : str)
(ch == '0' ) ? ++zeros : ++ones;
return (zeros == 1 || ones == 1);
}
int main()
{
canMakeAllSame( "101" ) ? printf ( "Yes\n" ) : printf ( "No\n" );
return 0;
}
|
Java
public class GFG {
static boolean canMakeAllSame(String str)
{
int zeros = 0 , ones = 0 ;
for ( int i = 0 ; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '0' )
++zeros;
else
++ones;
}
return (zeros == 1 || ones == 1 );
}
public static void main(String args[])
{
System.out.println(canMakeAllSame( "101" ) ? "Yes" : "No" );
}
}
|
Python3
def canMakeAllSame( str ):
zeros = 0
ones = 0
for i in range ( 0 , len ( str )):
ch = str [i];
if (ch = = '0' ):
zeros = zeros + 1
else :
ones = ones + 1
return (zeros = = 1 or ones = = 1 );
if (canMakeAllSame( "101" )):
print ( "Yes\n" )
else :
print ( "No\n" )
|
C#
using System;
class GFG {
static bool canMakeAllSame( string str)
{
int zeros = 0, ones = 0;
for ( int i = 0; i < str.Length; i++) {
char ch = str[i];
if (ch == '0' )
++zeros;
else
++ones;
}
return (zeros == 1 || ones == 1);
}
public static void Main()
{
Console.WriteLine(canMakeAllSame( "101" ) ? "Yes" : "No" );
}
}
|
Javascript
<script>
function canMakeAllSame(str)
{
let zeros = 0, ones = 0;
for (let i = 0; i < str.length; i++) {
let ch = str[i];
if (ch == '0' )
++zeros;
else
++ones;
}
return (zeros == 1 || ones == 1);
}
document.write(canMakeAllSame( "101" ) ? "Yes" : "No" );
</script>
|
PHP
<?php
function canMakeAllSame( $str )
{
$zeros = 0;
$ones = 0;
for ( $i =0; $i < strlen ( $str ); $i ++)
{
$ch = $str [ $i ];
if ( $ch == '0' )
++ $zeros ;
else
++ $ones ;
}
return ( $zeros == 1 || $ones == 1);
}
if (canMakeAllSame( "101" ) )
echo "Yes\n" ;
else echo "No\n" ;
return 0;
?>
|
Output:
Yes
Time complexity : O(n) where n is the length of the string.
Auxiliary Space: O(1)
Method 2 (Counting 0’s and 1’s)
The idea is to compute sum of all bits. If sum is n-1 or 1, then output is true, else false. This solution doesn’t require a comparison in a loop.
Below is the implementation of above idea.
C++
#include <bits/stdc++.h>
using namespace std;
bool isOneFlip(string str)
{
int sum = 0;
int n = str.length();
for ( int i = 0; i < n; i++)
sum += str[i] - '0' ;
return (sum == n - 1 || sum == 1);
}
int main()
{
isOneFlip( "101111111111" ) ? printf ( "Yes\n" ) : printf ( "No\n" );
return 0;
}
|
Java
public class GFG {
static boolean isOneFlip(String str)
{
int sum = 0 ;
int n = str.length();
for ( int i = 0 ; i < n; i++)
sum += str.charAt(i) - '0' ;
return (sum == n - 1 || sum == 1 );
}
public static void main(String args[])
{
System.out.println(isOneFlip( "101111111111" ) ? "Yes" : "No" );
}
}
|
Python3
def isOneFlip( str ):
sum = 0
n = len ( str )
for i in range ( 0 , n ):
sum + = int ( str [i]) - int ( '0' )
return ( sum = = n - 1 or sum = = 1 )
( print ( "Yes" ) if isOneFlip( "101111111111" )
else print ( "No" ))
|
C#
using System;
class GFG {
static bool isOneFlip( string str)
{
int sum = 0;
int n = str.Length;
for ( int i = 0; i < n; i++)
sum += str[i] - '0' ;
return (sum == n - 1 || sum == 1);
}
public static void Main()
{
Console.WriteLine(isOneFlip( "101111111111" ) ? "Yes" : "No" );
}
}
|
Javascript
<script>
function isOneFlip(str)
{
let sum = 0;
let n = str.length;
for (let i = 0; i < n; i++)
sum += str[i] - '0' ;
return (sum == n - 1 || sum == 1);
}
document.write(isOneFlip( "101111111111" ) ?
"Yes" : "No" );
</script>
|
PHP
<?php
function isOneFlip( $str )
{
$sum = 0;
$n = strlen ( $str );
for ( $i = 0; $i < $n ; $i ++)
$sum += $str [ $i ] - '0' ;
return ( $sum == $n - 1 || $sum == 1);
}
if (isOneFlip( "101111111111" ) )
echo "Yes\n" ;
else
echo "No\n" ;
?>
|
Output:
Yes
Time Complexity: O(N)
Auxiliary Space: O(1)
Thanks to Sourabh Gavhale for suggesting this solution
Method 3 (Iterating through string)
The idea is to iterate through the string and for each position, check if flipping that bit would make all the bits in the string the same. If yes, then return true, else continue iterating. If no such position is found, return false.
Below is the implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
bool isOneFlip(string str)
{
int n = str.length();
for ( int i = 0; i < n; i++) {
str[i] = (str[i] == '0' ) ? '1' : '0' ;
bool allSame = true ;
char firstBit = str[0];
for ( int j = 1; j < n; j++) {
if (str[j] != firstBit) {
allSame = false ;
break ;
}
}
if (allSame) {
return true ;
}
str[i] = (str[i] == '0' ) ? '1' : '0' ;
}
return false ;
}
int main()
{
isOneFlip( "101" ) ? printf ( "Yes\n" ) : printf ( "No\n" );
return 0;
}
|
Java
import java.util.*;
public class Main {
public static boolean isOneFlip(String str) {
int n = str.length();
for ( int i = 0 ; i < n; i++) {
char currentBit = (str.charAt(i) == '0' ) ? '1' : '0' ;
StringBuilder modifiedStr = new StringBuilder(str);
modifiedStr.setCharAt(i, currentBit);
boolean allSame = true ;
char firstBit = modifiedStr.charAt( 0 );
for ( int j = 1 ; j < n; j++) {
if (modifiedStr.charAt(j) != firstBit) {
allSame = false ;
break ;
}
}
if (allSame) {
return true ;
}
}
return false ;
}
public static void main(String[] args) {
boolean result = isOneFlip( "101" );
System.out.println(result ? "Yes" : "No" );
}
}
|
Python3
def is_one_flip(s):
n = len (s)
for i in range (n):
s = s[:i] + ( '0' if s[i] = = '1' else '1' ) + s[i + 1 :]
all_same = True
first_bit = s[ 0 ]
for j in range ( 1 , n):
if s[j] ! = first_bit:
all_same = False
break
if all_same:
return True
s = s[:i] + ( '0' if s[i] = = '1' else '1' ) + s[i + 1 :]
return False
if is_one_flip( "101" ):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class Program
{
static bool IsOneFlip( string str)
{
int n = str.Length;
for ( int i = 0; i < n; i++)
{
str = str.Substring(0, i) + (str[i] == '0' ? '1' : '0' ) + str.Substring(i + 1);
bool allSame = true ;
char firstBit = str[0];
for ( int j = 1; j < n; j++)
{
if (str[j] != firstBit)
{
allSame = false ;
break ;
}
}
if (allSame)
{
return true ;
}
str = str.Substring(0, i) + (str[i] == '0' ? '1' : '0' ) + str.Substring(i + 1);
}
return false ;
}
static void Main()
{
Console.WriteLine(IsOneFlip( "101" ) ? "Yes" : "No" );
}
}
|
Time Complexity: O(N^2) in worst case
Auxiliary Space: O(1)
Method 4 (XOR approach)
The idea is to compute the XOR of all the bits in the string. If the XOR is either 0 or 1, then return true, else return false.
Below is the implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
bool isOneFlip(string str)
{
int n = str.length();
int xorVal = 0;
for ( int i = 0; i < n; i++) {
xorVal ^= (str[i] - '0' );
}
return (xorVal == 0 || xorVal == 1);
}
int main()
{
isOneFlip( "101" ) ? printf ( "Yes\n" ) : printf ( "No\n" );
return 0;
}
|
Java
import java.io.*;
public class GFG {
static boolean isOneFlip(String str) {
int n = str.length();
int xorVal = 0 ;
for ( int i = 0 ; i < n; i++) {
xorVal ^= (str.charAt(i) - '0' );
}
return (xorVal == 0 || xorVal == 1 );
}
public static void main(String[] args) {
if (isOneFlip( "101" )) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
}
}
|
Time Complexity: O(N)
Auxiliary Space: O(1)
This article is contributed by Aarti_Rathi and Subrata Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.