Python 2839.py
class Solution:
def canBeEqual(self, s1: str, s2: str) -> bool:
# just four combinations, let's check them manually
if s1 == s2:
return True
a,b,c,d = list(s1)
if c+b+a+d == s2:
return True
if c+d+a+b == s2:
return True
if a+d+c+b == s2:
return True
return False
Difficulty
and has an acceptance rate of about 62% (200k+ submissions).
Typical patterns to solve this problem:
- 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 determines whether two input strings can be made identical by applying a limited set of rearrangements. It follows a straightforward, constant-time strategy: first it checks for direct equality, then it extracts the four characters of the first string and compares the second string against three specific reordered forms. If any comparison succeeds, the function returns True; otherwise it returns False.
Core Logic
Direct Equality Check
The very first operation compares the two strings as they are received.
if s1 == s2:
return True
When the strings match exactly, the function terminates immediately, avoiding any further work.
Decomposition of the First String
The next step breaks the first string into four separate variables, assuming a length of four characters.
a, b, c, d = list(s1)
By assigning each character to a distinct name, the code can later construct the required permutations in a readable way.
Manual Permutation Comparisons
Three distinct rearrangements are examined. Each permutation is built by concatenating the previously extracted characters in a particular order and then compared with the second string.
if c + b + a + d == s2:
return True
if c + d + a + b == s2:
return True
if a + d + c + b == s2:
return True
If any of these concatenated forms equals s2, the function concludes that the strings can be made equal under the allowed transformations.
Default Return
When none of the earlier conditions hold, the function reaches the final statement and returns False.
return False
Edge Cases Handled
The implementation explicitly covers the scenario where the two strings are already identical, returning True without further processing. It also addresses the situation where the second string matches any of the three predefined rearrangements of the first string. By checking each permutation individually, the code ensures that all permissible configurations are considered.
Performance Characteristics
The algorithm operates in constant time because it performs a fixed number of operations regardless of input size. The early exit after a successful equality test prevents unnecessary work. The use of direct string concatenation for each permutation avoids the overhead of loops or auxiliary data structures, keeping the memory footprint minimal. By limiting the work to a handful of straightforward comparisons, the function achieves optimal efficiency for the defined problem space.
ELI5 - Simplified Explanation
Imagine you have two necklaces made of four colored beads. Sometimes people take the beads off and put them back in a different order, but they want to know if the necklaces could end up looking exactly the same eventually.
This code acts like a tiny helper that looks at the first necklace and tries out a few ways to swap the beads around. It takes the four beads and checks if swapping the first and third ones, swapping the middle ones, or swapping the outside ones makes the first necklace match the second one. If any of those quick shuffles match the second necklace, the code says yes. If it tries all those specific ways and still cannot make them match, it says no. It is basically just playing a game of moving pieces around until the puzzle matches.
Code Quality
Complexity Analysis
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 | Java | C++ | Python | TS | ||||
| WalkCCC | Java | C++ | Python | ||||||
| leetcode.ca | Java | C++ | Go | Python | Rust | TS | |||
| Progiez | Java | C++ | Python | ||||||
| github | AdelDaniel | Dart | |||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| AdelDaniel | Dart | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 2840: Check if Strings Can be Made Equal With Operations II
Solved On The Same Day
- problem 1752: Check if Array Is Sorted and Rotated
- problem 1791: Find Center of Star Graph
- problem 1971: Find if Path Exists in Graph
- problem 1984: Minimum Difference Between Highest and Lowest of K Scores
- problem 2446: Determine if Two Events Have Conflict
- problem 2706: Buy Two Chocolates
- problem 684: Redundant Connection
- problem 1008: Construct Binary Search Tree from Preorder Traversal
- problem 1026: Maximum Difference Between Node and Ancestor
- problem 1034: Coloring A Border
- problem 1625: Lexicographically Smallest String After Applying Operations
- problem 1765: Map of Highest Peak
- problem 2192: All Ancestors of a Node in a Directed Acyclic Graph
- problem 2477: Minimum Fuel Cost to Report to the Capital
- problem 2492: Minimum Score of a Path Between Two Cities
- problem 2596: Check Knight Tour Configuration
- problem 2658: Maximum Number of Fish in a Grid
- problem 827: Making A Large Island
- problem 1036: Escape a Large Maze
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