#2546

Apply Bitwise Operations to Make Strings Equal

Medium
StringBit ManipulationBit ManipulationGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the properties of binary strings and bitwise operations. We can determine if transformation is possible by checking the presence of '1's in both strings. If both strings have at least one '1' or both are all '0's, transformation is possible.

⚙️

Algorithm

2 steps
  1. 1Step 1: Count the number of '1's in both `s` and `target`.
  2. 2Step 2: If both counts are non-zero or both are zero, return true; otherwise, return false.
solution.py2 lines
1def canMakeEqual(s, target):
2    return (s.count('1') > 0 and target.count('1') > 0) or (s.count('1') == 0 and target.count('1') == 0)

Complexity note: This complexity is linear because we are simply counting the number of '1's in each string, which requires a single pass through each string.

  • 1If both strings have at least one '1', transformation is possible.
  • 2If both strings are all '0's, transformation is also possible.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.