Apply Bitwise Operations to Make Strings Equal - 4 Observations [JS]
Solution: 4 Observations
Outcomes of the 4 different situations:
11 -> 10
10 -> 11
01 -> 11
00 -> 00
Observations:
- If
s
only has"0"
s and target has a"1"
, it is impossible because we can never get a"1"
from"0"
s. - No matter how many
"1"
s we try to remove, there will always be one left because11 -> 10
. Therefore ifs
has"1"
s and target has only"0"
s, it is impossible. - As long as we have at least one
"1"
, we can produce as many or at little"1"
s as we like (must be more than0
).- Getting more
"1"
s:01 -> 11
,10 -> 11
. - Getting less
"1"
s:11 -> 10
, and11 -> 01
if we flip the order of(i, j)
.
- Getting more
- Notice there is a cycle (
11 -> 10
,10 -> 11
). Because the order of(i, j)
doesn't matter, this cycle applies for the opposite direction also. This means we can swap the order of10 -> 01
,01 -> 10
however we want. Swapping means we can order in any way possible.
To summarize the last two observations, as long as we have at least one "1"
in s, we can produce as many "1"
s as we need and order s
in any way.
Time Complexity: O(n)
Space Complexity: O(1)
var makeStringsEqual = function(s, target) {
if (!s.includes("1") && target.includes("1")) return false;
if (s.includes("1") && !target.includes("1")) return false;
return true;
};
Comments
Post a Comment