MediumNo. 1657

Determine if Two Strings Are Close — LeetCode 1657 Python Solution

Pattern
Sorting
Topics
Hash Table, String, Counting, Sorting
On a study list
LeetCode 75
Reading time
2 min

The problem

Two strings are considered close if you can attain one from the other using the following operations: Operation 1: Swap any two existing characters. For example, abcde -> aecdb Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.

Example

Input
word1 = "abc", word2 = "bca"
Output
true
Explanation
You can attain word2 from word1 in 2 operations.

Python solution

PythonSolution
class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        cnt1, cnt2 = Counter(word1), Counter(word2)
        return sorted(cnt1.values()) == sorted(cnt2.values()) and set(
            cnt1.keys()
        ) == set(cnt2.keys())

Complexity

Time
O(m + n + C × log C)
Space · auxiliary
O(C)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1657. Determine if Two Strings Are Close 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 1657. Determine if Two Strings Are Close?

LeetCode 1657. Determine if Two Strings Are Close is rated Medium on LeetCode.

What is the time complexity of LeetCode 1657. Determine if Two Strings Are Close?

The Python solution on this page runs in O(m + n + C × log C).

What is the space complexity of LeetCode 1657. Determine if Two Strings Are Close?

The Python solution on this page uses O(C) auxiliary space.

What topics does LeetCode 1657. Determine if Two Strings Are Close cover?

LeetCode 1657. Determine if Two Strings Are Close is tagged Hash Table, String, Counting 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.

Free to download. Check it runs on your machine, then pick a plan.