Apply Bitwise Operations to Make Strings Equal - 4 Observations [JS]

Description 

Solution: 4 Observations

Outcomes of the 4 different situations:

  1. 11 -> 10
  2. 10 -> 11
  3. 01 -> 11
  4. 00 -> 00

Observations:

  1. If s only has "0"s and target has a "1", it is impossible because we can never get a "1" from "0"s.
  2. No matter how many "1"s we try to remove, there will always be one left because 11 -> 10. Therefore if s has "1"s and target has only "0"s, it is impossible.
  3. 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 than 0).
    • Getting more "1"s: 01 -> 1110 -> 11.
    • Getting less "1"s: 11 -> 10, and 11 -> 01 if we flip the order of (i, j).
  4. Notice there is a cycle (11 -> 1010 -> 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 of 10 -> 0101 -> 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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]