PROBLEM LINK:
Author: Chandan Boruah
Tester: Praveen Dhinwa
Editorialist: Ajay K. Verma
DIFFICULTY:
Cakewalk
PREREQUISITES:
Ad-hoc, String
PROBLEM:
Given a binary string, find if it is possible to make all its digits equal by flipping exactly one digit.
QUICK EXPLANATION:
All the digits of the binary string can be made equal by flipping exactly one digit if and only if the original string has exactly one digit equal to zero, or exactly one digit equal to one.
EXPLANATION:
Suppose that the input string has exactly one digit equal to one, and all other digits are zero, then we can flip this digit, which will result in a string with all digits equal to zero. Similarly, if the input string has exactly one digit equal to zero, and all other digits are one, then flipping this digit would result in a string with all digits equal to one.
On the other hand, 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 one 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.
void f(string str) { int num_zeros = 0; int num_ones = 0; for (char ch : str) { if (ch == '0') { ++num_zeros; } else { ++num_ones; } } if (num_zeros == 1 || num_ones == 1) { print("Yes\n"); } else { print("No\n"); } }
TIME COMPLEXITY:
O (N), where N is the length of the string.
AUTHOR’S AND TESTER’S SOLUTIONS:
Author’s solution will be uploaded soon.
Tester’s solution will be uploaded soon.