Apply Bitwise Operations to Make Strings Equal - Problem

You are given two 0-indexed binary strings s and target of the same length n. You can do the following operation on s any number of times:

Choose two different indices i and j where 0 <= i, j < n.

Simultaneously replace s[i] with (s[i] OR s[j]) and s[j] with (s[i] XOR s[j]).

For example, if s = "0110", you can choose i = 0 and j = 2, then simultaneously replace s[0] with (s[0] OR s[2] = 0 OR 1 = 1), and s[2] with (s[0] XOR s[2] = 0 XOR 1 = 1), so we will have s = "1110".

Return true if you can make the string s equal to target, or false otherwise.

Input & Output

Example 1 — Basic Transformation
$ Input: s = "1010", target = "1100"
Output: true
💡 Note: Choose i=1, j=2: s[1] OR s[2] = 1|1 = 1, s[1] XOR s[2] = 1^1 = 0. Result: "1100"
Example 2 — Impossible Case
$ Input: s = "0000", target = "1100"
Output: false
💡 Note: Since s has no 1s, we cannot create any 1s using OR/XOR operations
Example 3 — Already Equal
$ Input: s = "1111", target = "1111"
Output: true
💡 Note: s already equals target, no operations needed

Constraints

  • 1 ≤ s.length ≤ 105
  • s.length == target.length
  • s and target consist of only '0' and '1'

Visualization

Tap to expand
Bitwise Operations to Make Strings Equal INPUT String s: 1 0 1 0 idx: 0 1 2 3 String target: 1 1 0 0 idx: 0 1 2 3 Operations Available: s[i] = s[i] OR s[j] s[j] = s[i] XOR s[j] (simultaneously) ALGORITHM STEPS 1 Count 1s in both strings s has 2 ones, target has 2 2 Check special case Both all-zeros? Return true 3 Key observation If s has any 1, we can spread/move it anywhere 4 Final check s has 1 AND target has 1? Return true, else false Operation Truth Table i,j | OR XOR 0,0 | 0 0 0,1 | 1 1 1,0 | 1 1 1,1 | 1 0 FINAL RESULT Analysis: s = "1010" has at least one 1 target = "1100" has at least one 1 Transformation Possible: 1 0 1 0 --> 1 1 0 0 Output: true Key Insight: With the given operations (OR and XOR), if we have at least one '1' in string s, we can propagate it to any position and also eliminate 1s by using XOR. The transformation is possible if and only if both strings contain at least one '1', OR both are all zeros. Time: O(n), Space: O(1) TutorialsPoint - Apply Bitwise Operations to Make Strings Equal | Optimal Solution
Asked in
Google 15 Meta 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
387 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen