Check if Strings Can be Made Equal With Operations I — LeetCode 2839 Python Solution

EasyString
Problem
#2839
Pattern
Hash Map
Reading time
2 min

The problem

You are given two strings s1 and s2, both of length 4, consisting of lowercase English letters. You can apply the following operation on any of the two strings any number of times: Choose any two indices i and j such that j - i = 2, then swap the two characters at those indices in the string.

Example

Input
s1 = "abcd", s2 = "cdab"
Output
true
Explanation
We can do the following operations on s1:

Python solution

Python
class Solution:
    def canBeEqual(self, s1: str, s2: str) -> bool:
        return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted(
            s2[1::2]
        )

Complexity

MeasureComplexity
TimeO(n + |\Sigma|)
SpaceO(|\Sigma|) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2839. Check if Strings Can be Made Equal With Operations I is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2839. Check if Strings Can be Made Equal With Operations I?
LeetCode 2839. Check if Strings Can be Made Equal With Operations I is rated Easy on LeetCode.
What is the time complexity of LeetCode 2839. Check if Strings Can be Made Equal With Operations I?
The Python solution on this page runs in O(n + |\Sigma|).
What is the space complexity of LeetCode 2839. Check if Strings Can be Made Equal With Operations I?
The Python solution on this page uses O(|\Sigma|) auxiliary space.
What topics does LeetCode 2839. Check if Strings Can be Made Equal With Operations I cover?
LeetCode 2839. Check if Strings Can be Made Equal With Operations I is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview