Groups of Special-Equivalent Strings — LeetCode 893 Python Solution

MediumArrayHash TableStringSorting
Problem
#893
Pattern
Sorting
Reading time
2 min

The problem

You are given an array of strings of the same length words. In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i].

Example

Input
words = ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output
3
Explanation
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.

Python solution

Python
class Solution:
    def numSpecialEquivGroups(self, words: List[str]) -> int:
        s = {''.join(sorted(word[::2]) + sorted(word[1::2])) for word in words}
        return len(s)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 893. Groups of Special-Equivalent Strings 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 893. Groups of Special-Equivalent Strings?
LeetCode 893. Groups of Special-Equivalent Strings is rated Medium on LeetCode.
What is the time complexity of LeetCode 893. Groups of Special-Equivalent Strings?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 893. Groups of Special-Equivalent Strings?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 893. Groups of Special-Equivalent Strings cover?
LeetCode 893. Groups of Special-Equivalent Strings is tagged Array, 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