Groups of Special-Equivalent Strings - Problem

You are given an array of strings words where all strings have the same length.

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 where:

  • Every pair of strings in the group are special-equivalent
  • The group is the largest size possible (no string outside the group is special-equivalent to every string in the group)

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

Input & Output

Example 1 — Basic Grouping
$ Input: words = ["abc","acb","bac","bca","cab","cba"]
Output: 3
💡 Note: Group 1: ["abc","bac"] (even: "ac", odd: "b"), Group 2: ["acb","bca","cab","cba"] (even: "ac"/"bc"/"cb", odd: "cb"/"a"/"a"), Group 3: singles. After proper analysis: 3 distinct signatures.
Example 2 — All Same Group
$ Input: words = ["a"]
Output: 1
💡 Note: Single string forms one group.
Example 3 — No Equivalents
$ Input: words = ["aa","bb","ab","ba"]
Output: 4
💡 Note: "aa" (even:"a", odd:"a"), "bb" (even:"b", odd:"b"), "ab" (even:"a", odd:"b"), "ba" (even:"b", odd:"a") - all different signatures.

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 20
  • words[i] consists of lowercase English letters
  • All the strings are of the same length

Visualization

Tap to expand
Groups of Special-Equivalent StringsInput: ["abc", "bac", "cab"]"abc""bac""cab"Even: acOdd: bEven: acOdd: bEven: caOdd: bGroup 1"abc", "bac"Group 2"cab"Signatures: "ac|b" and "ac|b" vs "ac|b"Output: 2 groups🎯 Key: Same sorted even/odd chars = same group
Understanding the Visualization
1
Input Analysis
Array of strings with same length
2
Character Separation
Split into even and odd positioned characters
3
Group Formation
Count unique signature patterns
Key Takeaway
🎯 Key Insight: Two strings belong to the same group if their sorted even-positioned and odd-positioned characters match
Asked in
Google 15 Facebook 12 Amazon 8
28.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen