Apply Bitwise Operations to Make Strings Equal - Problem
Binary String Transformation Challenge

You're given two 0-indexed binary strings s and target of the same length n. Your goal is to determine if you can transform string s into the target string using a special bitwise operation.

The Operation: You can choose any two different indices i and j and simultaneously perform:
• Replace s[i] with (s[i] OR s[j])
• Replace s[j] with (s[i] XOR s[j])

Example: If s = "0110", choosing i = 0 and j = 2:
s[0] becomes (0 OR 1) = 1
s[2] becomes (0 XOR 1) = 1
• Result: s = "1110"

Return true if transformation is possible, false otherwise.

Input & Output

example_1.py — Basic Transformation
$ Input: s = "1010", target = "0110"
Output: true
💡 Note: Both strings have 2 ones, and s contains 1s, so transformation is possible. We can rearrange the 1s to match the target pattern.
example_2.py — Impossible Case
$ Input: s = "0000", target = "1111"
Output: false
💡 Note: s has no 1s, but target has 1s. Since we cannot create 1s from all 0s using the given operations, transformation is impossible.
example_3.py — Edge Case
$ Input: s = "1111", target = "0000"
Output: false
💡 Note: While s has 1s, we cannot eliminate all 1s to reach a target of all 0s. The operation maintains at least one 1 when starting with 1s.

Visualization

Tap to expand
Bitwise Transformation AnalysisThe Operations[i] ← s[i] OR s[j]s[j] ← s[i] XOR s[j](Applied simultaneously)No 1s in Source0000 → ?0 OR 0 = 00 XOR 0 = 0Result: Still 0000Has 1s in Source1010 → many optionsCan rearrange 1sCannot eliminate allResult: Any non-zeroExamples1,0 → 1,1 (OR,XOR)1,1 → 1,00,1 → 1,10,0 → 0,0Notice: 1s preservedKey InsightCount 1s in source: 0 → only reach all-zero target, >0 → reach any non-zero target
Understanding the Visualization
1
Operation Definition
s[i] = s[i] OR s[j], s[j] = s[i] XOR s[j] simultaneously
2
Case Analysis
If source has no 1s: cannot create 1s. If source has 1s: can reach non-zero targets
3
Mathematical Proof
OR operation can only maintain or create 1s, never eliminate all 1s when they exist
Key Takeaway
🎯 Key Insight: The operation preserves the fundamental property of having 1s. We can solve this in O(n) time by simply counting 1s instead of simulating operations.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through both strings to analyze bit patterns

n
2n
Linear Growth
Space Complexity
O(1)

Only using a few variables to track counts and patterns

n
2n
Linear Space

Constraints

  • n == s.length == target.length
  • 1 ≤ n ≤ 105
  • s and target consist of only '0' and '1'
  • Both strings are binary strings of equal length
Asked in
Google 12 Meta 8 Amazon 6 Microsoft 4
28.5K Views
Medium Frequency
~15 min Avg. Time
890 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