Python 2546.py
class Solution:
def makeStringsEqual(self, s: str, target: str) -> bool:
# 0 OR 0 == 0, 0 XOR 0 == 0
# 0 OR 1 == 1, 0 XOR 1 == 1
# 1 OR 0 == 1, 1 XOR 0 == 1
# 1 OR 1 == 1, 1 XOR 1 == 0
# if target contains "0" but source is "1" at the same index,
# then we need at least one "1" in source to convert it to "0"
# (with 1 XOR 1 == 0), there's no other way
# any other bit pattern can be easily created
return ("1" in s and "1" in target) or s == target
Difficulty
and has an acceptance rate of about 43% (50k+ submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a single method makeStringsEqual that decides whether two binary strings s and target can be made identical using a specific set of bitwise operations. The core of the solution is a concise Boolean expression that captures the necessary condition for transformability. The method returns True when the condition holds and False otherwise.
Core Logic
The algorithm hinges on two observations about the allowed operations:
- Converting a
1to a0requires the presence of another1in the source string, because the only way to produce a0from a1is by applying XOR between two1s (1 XOR 1 == 0). - If both strings contain at least one
1, any pattern of bits can be generated by appropriate sequences of OR and XOR operations.
These observations are encoded in the following return statement:
return ("1" in s and "1" in target) or s == target
The expression consists of two parts combined with logical OR:
("1" in s and "1" in target)- checks that each string has at least one1. When this is true, the algorithm asserts that the transformation is always possible.s == target- handles the situation where the strings are already identical, regardless of their content.
If either part evaluates to True, the method concludes that the strings can be made equal.
Detailed Walkthrough
Presence Check
The first sub-expression uses the membership operator in to scan each string for the character '1'. The evaluation proceeds as follows:
if "1" in s:
# continue checking target
if "1" in target:
# both strings contain a '1'
return True
Because Python’s and operator short-circuits, the second membership test is performed only when the first test succeeds. This avoids an unnecessary scan of target when s lacks any 1s.
Equality Shortcut
If the presence check fails, the expression falls back to a direct equality comparison:
if s == target:
return True
When the strings are already the same, no transformation steps are required, and the method can immediately return True.
Final Result
When neither the presence condition nor the equality condition holds, the method returns False. This corresponds to cases where s lacks a 1 but target contains a 1, making it impossible to generate the required 1 bits.
Edge Cases Handled
- Both strings consist solely of
0s - The presence check fails for both strings, but the equality check succeeds, resulting inTrue. - Identical strings containing a mixture of
0s and1s - The equality check short-circuits the evaluation, returningTruewithout examining the presence condition. - Source string contains at least one
1while target does not - The presence condition is satisfied because both strings contain a1(the source does, the target does not, so the condition fails). The equality check fails, leading toFalse. This correctly reflects that a1cannot be eliminated without another1in the source. - Target string contains a
1while source does not - The presence condition fails because the source lacks a1. The equality check also fails, yieldingFalse. This captures the impossibility of creating a1from an all-zero source. - Both strings contain at least one
1but differ - The presence condition succeeds, and the method returnsTrue, indicating that the required transformations are feasible.
Performance Optimizations
The implementation leverages Python’s built-in string membership test, which scans the string until the first occurrence of '1'. This early-exit behavior minimizes work when a 1 appears near the beginning of the string. The logical and operator further reduces work by preventing the second scan when the first string lacks a 1.
The equality comparison s == target is also optimized by Python: it first checks object identity and length before performing a character-by-character comparison, allowing a fast exit for unequal length strings.
Overall, the method performs at most two linear scans of the input strings, each of which stops as soon as the required condition is met. This yields an efficient solution that scales linearly with the length of the inputs while keeping constant additional memory usage.
ELI5 - Simplified Explanation
Imagine you have two rows of light switches. One row is called the source and the other is called the target. Some switches are flipped up to show a one and some are flipped down to show a zero. You are allowed to take two switches from the source row and change them based on a special rule. If both switches are down, they stay down. If one is up and one is down, you can make them both be up. If both are up, you can make one stay up and turn the other one down.
When you want to see if the source row can eventually look exactly like the target row, you look for a way to use the ones you already have. Because you can use the ones to change other switches, as long as you have at least one switch turned up in both rows, you can reach the target state. If the source row is already a perfect match for the target row, that works out just fine too. The code checks these two simple ideas to see if the transformation is possible.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | C | Go | Rust | TS | ||
| Progiez | C++ | Python | Java | ||||||
| github | charles-wangkai | Java | |||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 1611: Minimum One Bit Operations to Make Integers Zero
Solved On The Same Day
- problem 2488: Count Subarrays With Median K
- problem 2538: Difference Between Maximum and Minimum Price Sum
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality