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
- Source
- leetcode.com
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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0451 | Sort Characters By Frequency | Medium |
| 0692 | Top K Frequent Words | Medium |
| 0767 | Reorganize String | Medium |
| 1366 | Rank Teams by Votes | Medium |
| 1647 | Minimum Deletions to Make Character Frequencies Unique | Medium |
| 0049 | Group Anagrams | Medium |
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.