Determine if Two Strings Are Close — LeetCode 1657 Python Solution

MediumHash TableStringCountingSorting
Problem
#1657
Pattern
Sorting
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

Python
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

MeasureComplexity
TimeO(m + n + C \times \log C)
SpaceO(C) auxiliary

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

On a study list

This problem is on LeetCode 75.

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 \times \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.

Get Stealth Interview