Check if Strings Can be Made Equal With Operations II — LeetCode 2840 Python Solution

MediumHash TableStringSorting
Problem
#2840
Pattern
Sorting
Reading time
2 min

The problem

You are given two strings s1 and s2, both of length n, 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 i < j and the difference j - i is even, then swap the two characters at those indices in the string.

Example

Input
s1 = "abcdba", s2 = "cabdab"
Output
true
Explanation
We can apply the following operations on s1:

Python solution

Python
class Solution:
    def checkStrings(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: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2840. Check if Strings Can be Made Equal With Operations II is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2840. Check if Strings Can be Made Equal With Operations II?
LeetCode 2840. Check if Strings Can be Made Equal With Operations II is rated Medium on LeetCode.
What is the time complexity of LeetCode 2840. Check if Strings Can be Made Equal With Operations II?
The Python solution on this page runs in O(n + |\Sigma|).
What is the space complexity of LeetCode 2840. Check if Strings Can be Made Equal With Operations II?
The Python solution on this page uses O(|\Sigma|) auxiliary space.
What topics does LeetCode 2840. Check if Strings Can be Made Equal With Operations II cover?
LeetCode 2840. Check if Strings Can be Made Equal With Operations II is tagged Hash Table, String and Sorting 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