# Leetcode: Groups of Special-Equivalent Strings

Groups of Special-Equivalent Strings

Similar Problems:

You are given an array A of strings.

Two strings S and T are special-equivalent if after any number of moves, S == T.

A move consists of choosing two indices i and j with i % 2 == j % 2, and swapping S[i] with S[j].

Now, a group of special-equivalent strings from A is a non-empty subset S of A such that any string not in S is not special-equivalent with any string in S.

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

Example 1:

```Input: ["a","b","c","a","c","c"]
Output: 3
Explanation: 3 groups ["a","a"], ["b"], ["c","c","c"]
```

Example 2:

```Input: ["aa","bb","ab","ba"]
Output: 4
Explanation: 4 groups ["aa"], ["bb"], ["ab"], ["ba"]
```

Example 3:

```Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
Explanation: 3 groups ["abc","cba"], ["acb","bca"], ["bac","cab"]
```

Example 4:

```Input: ["abcd","cdab","adcb","cbad"]
Output: 1
```

Note:

1. 1 <= A.length <= 1000
2. 1 <= A[i].length <= 20
3. All A[i] have the same length.
4. All A[i] consist of only lowercase letters.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

• Solution: odd/even group with sort
```// Blog link: https://code.dennyzhang.com/groups-of-special-equivalent-strings
// Basic Ideas: odd/even groups
// Complexity: Time O(n), Space O(n)
import (
"sort"
"strings"
)
func numSpecialEquivGroups(A []string) int {
m := map[string]bool{}
for _, s := range A {
l1, l2 := []string{}, []string{}
for i, ch := range s {
if i % 2 == 0 {
l1 = append(l1, string(ch))
} else {
l2 = append(l2, string(ch))
}
}
sort.Strings(l1)
sort.Strings(l2)
key := strings.Join(l1, "")+":"+strings.Join(l2, "")
m[key] = true
}
return len(m)
}
```

• Solution: odd/even group without sort
```// Blog link: https://code.dennyzhang.com/groups-of-special-equivalent-strings
// Basic Ideas: odd/even groups without sort
// array of 52 positions.
// First part for odd ones, the other for even ones.
// Complexity: Time O(n), Space O(n)
func numSpecialEquivGroups(A []string) int {
m := map[[52]int]bool{}
for _, s := range A {
key := [52]int{}
for j, ch := range s {
if j % 2 == 0 {
key[byte(ch)-'a']++
} else {
key[byte(ch)-'a'+26]++
}
}
m[key] = true
}
return len(m)
}
```

• Solution: with 26 positions, instead of 52
```// Blog link: https://code.dennyzhang.com/groups-of-special-equivalent-strings
// Basic Ideas: odd/even groups without sort
// array of 26 positions.
// First part for odd ones, the other for even ones.
// Complexity: Time O(n), Space O(n)
func numSpecialEquivGroups(A []string) int {
m := map[[26]int]bool{}
for _, s := range A {
key := [26]int{}
for i, ch := range s {
if i % 2 == 0 {
key[byte(ch)-'a'] += 1
} else {
key[byte(ch)-'a'] += 100
}
}
m[key] = true
}
return len(m)
}
```

Share It, If You Like It.