Problem 2839

Abstract / Summary

Check if two strings can become equal by repeatedly removing the last character from either string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
15 lines | 388 bytes | submitted December 20, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 62% (200k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.27 | σ = 2.12

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
22 links | 10 authors | 8 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

20 solutions   December 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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