Skip to main content

Groups of Special-Equivalent Strings - Solution & Explanation

MediumArrayHash TableStringSorting15 min readAsked at: Meta
Practice this problem

Problem Statement

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].

Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j].

  • For example, words[i] = "zzxy" and words[j] = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz".

A group of special-equivalent strings from words is a non-empty subset of words such that:

  • Every pair of strings in the group are special equivalent, and
  • The group is the largest size possible (i.e., there is not a string words[i] not in the group such that words[i] is special-equivalent to every string in the group).

Return the number of groups of special-equivalent strings from words.

 

Example 1:

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.
The other two groups are ["xyzz", "zzxy"] and ["zzyx"].
Note that in particular, "zzxy" is not special equivalent to "zzyx".

Example 2:

Input: words = ["abc","acb","bac","bca","cab","cba"]
Output: 3

 

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 20
  • words[i] consist of lowercase English letters.
  • All the strings are of the same length.

Approach Overview

Problem Overview: You receive an array of strings. Two strings are special-equivalent if you can swap characters among even indices or among odd indices any number of times and transform one string into the other. The task is to count how many distinct groups of such equivalent strings exist.

Approach 1: Group by Sorted Characters (O(n * k log k) time, O(n * k) space)

The allowed swaps mean characters at even indices can rearrange among themselves, and characters at odd indices can rearrange among themselves. For each string, split characters into two buckets: even-indexed and odd-indexed. Sort both buckets independently and combine them into a canonical key such as sortedEven + '#' + sortedOdd. Insert this key into a hash set to track unique groups. If two strings produce the same key, they belong to the same special-equivalent group. This method relies on sorting to normalize both parity positions and uses a hash table or set for grouping.

Approach 2: Character Frequency Counting (O(n * k) time, O(n) space)

Sorting is not strictly necessary. Since characters only rearrange within parity groups, the exact order is irrelevant; only the counts matter. For each string, build two frequency arrays of size 26: one for even positions and one for odd positions. Concatenate the counts into a compact signature (for example, a tuple or string). Insert this signature into a hash set to represent the group. Two strings with identical even and odd frequency distributions must be special-equivalent. This avoids sorting entirely and reduces the complexity to linear time per string. The solution heavily uses array indexing and string processing.

Recommended for interviews: Character Frequency Counting is usually the expected solution. It demonstrates recognition that order does not matter within parity groups and reduces the cost from k log k sorting to linear counting. The sorting approach still works and is easier to implement quickly, which makes it a good starting point during interviews before optimizing.

Approach 1: Group by Sorted Characters

This approach involves separating each word into two groups of characters: those at even indices and those at odd indices. By sorting the characters in each group and forming a tuple of the sorted results, we establish a unique signature for special-equivalent strings. We then use a set to keep track of unique signatures, as duplicate tuples will represent special-equivalent strings.

The solution involves splitting each word into even-indexed and odd-indexed characters, sorting them separately, and joining the sorted results to create a signature. Unique signatures are stored in a set, representing different groups.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(N * M log M) where N is the number of words and M is the length of each word since each word is processed and sorted.
Space Complexity: O(N * M) to store unique signatures.

Try this approach in the editor →

Approach 2: Character Frequency Counting

This approach uses character frequency counts rather than sorting. By counting occurrences of each character in even and odd positions separately, we can determine if two strings are special-equivalent. Each string creates two frequency maps (or equivalent structures), and these are combined into a single representation for comparison across all words.

In the C solution, we count frequencies of each character at even and odd indices separately. These counts are stored in a byte array (signature) which acts as a hash map for comparing each word.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(N * M) since we do not sort but loop through each word twice.
Space Complexity: O(N * 52) since we store only a fixed size (26 even and 26 odd).

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Group by Sorted Characters

Time Complexity: O(N * M log M) where N is the number of words and M is the length of each word since each word is processed and sorted.
Space Complexity: O(N * M) to store unique signatures.

Character Frequency Counting

Time Complexity: O(N * M) since we do not sort but loop through each word twice.
Space Complexity: O(N * 52) since we store only a fixed size (26 even and 26 odd).

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Group by Sorted Even/Odd CharactersO(n * k log k)O(n * k)Simpler implementation when sorting cost is acceptable
Character Frequency CountingO(n * k)O(n)Optimal approach when string length is large and sorting overhead should be avoided

Video Solution

LeetCode 99 Problem 2 - Groups of Special-Equivalent Strings (893) • code_report • 2,489 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Groups of Special-Equivalent Strings easy or hard?
The problem is rated Medium because the key insight is recognizing that swaps only occur within even and odd positions. Once you convert each string into a canonical parity-based representation, grouping becomes straightforward using hashing.
Groups of Special-Equivalent Strings Python/Java solution
In Python, create two lists of size 26 for even and odd frequencies and store the tuple of counts in a set. In Java, use two int[26] arrays and convert them to a string key or use Arrays.toString. Both implementations group strings using a hash-based structure.
How to solve Groups of Special-Equivalent Strings in O(n)?
Process each string once and build two frequency arrays for even and odd positions. Combine these counts into a unique key and insert it into a hash set. Because each character is processed exactly once, the work per string is O(k), giving total complexity O(n * k).
What is the best approach for Groups of Special-Equivalent Strings?
The most efficient approach uses character frequency counting for even and odd indices separately. For each string, build two frequency arrays of size 26 and use them as a canonical signature in a hash set. Strings with identical parity frequency distributions belong to the same group. This runs in O(n * k) time where n is the number of strings and k is the string length.
Is Groups of Special-Equivalent Strings asked at Google/Amazon/Meta?
Problems involving string normalization and hash-based grouping appear frequently in interviews at companies like Google, Amazon, and Meta. Variants that require grouping strings by structural equivalence or canonical representation are common interview patterns.
What data structure is used in Groups of Special-Equivalent Strings?
A hash set or hash map stores canonical representations of each string's parity structure. Arrays are used for frequency counting of characters at even and odd indices, and strings or tuples act as unique group keys.
What is the time complexity of Groups of Special-Equivalent Strings?
The optimal solution runs in O(n * k) time using character frequency counting for even and odd indices. A simpler implementation sorts characters at even and odd positions separately, which costs O(n * k log k). Both approaches require storing group signatures in a hash set.

Ready to solve this problem?

Practice Groups of Special-Equivalent Strings with our built-in code editor and test cases.

Practice on FleetCode