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.
Explanation: In 101, the 0 can be flipped
to make it all 1
Explanation: No matter whichever digit you
flip, you will not get the desired string.
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.
// This code is contributed by avanitrachhadiya2155
Time Complexity: O(N) Auxiliary Space: O(1) Thanks to Sourabh Gavhale for suggesting this solution
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 email@example.com. 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.
Please Login to comment...