Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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].
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:
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 <= 10001 <= words[i].length <= 20words[i] consist of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
["abc","acb","bac","bca","cab","cba"]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #893: Groups of Special-Equivalent Strings
class Solution {
public int numSpecialEquivGroups(String[] words) {
Set<String> s = new HashSet<>();
for (String word : words) {
s.add(convert(word));
}
return s.size();
}
private String convert(String word) {
List<Character> a = new ArrayList<>();
List<Character> b = new ArrayList<>();
for (int i = 0; i < word.length(); ++i) {
char ch = word.charAt(i);
if (i % 2 == 0) {
a.add(ch);
} else {
b.add(ch);
}
}
Collections.sort(a);
Collections.sort(b);
StringBuilder sb = new StringBuilder();
for (char c : a) {
sb.append(c);
}
for (char c : b) {
sb.append(c);
}
return sb.toString();
}
}
// Accepted solution for LeetCode #893: Groups of Special-Equivalent Strings
func numSpecialEquivGroups(words []string) int {
s := map[string]bool{}
for _, word := range words {
a, b := []rune{}, []rune{}
for i, c := range word {
if i&1 == 1 {
a = append(a, c)
} else {
b = append(b, c)
}
}
sort.Slice(a, func(i, j int) bool {
return a[i] < a[j]
})
sort.Slice(b, func(i, j int) bool {
return b[i] < b[j]
})
s[string(a)+string(b)] = true
}
return len(s)
}
# Accepted solution for LeetCode #893: Groups of Special-Equivalent Strings
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)
// Accepted solution for LeetCode #893: Groups of Special-Equivalent Strings
struct Solution;
use std::collections::BTreeMap;
use std::collections::HashSet;
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
struct Count {
even: BTreeMap<char, usize>,
odd: BTreeMap<char, usize>,
}
impl Count {
fn new(s: String) -> Self {
let mut even: BTreeMap<char, usize> = BTreeMap::new();
let mut odd: BTreeMap<char, usize> = BTreeMap::new();
for (i, c) in s.chars().enumerate() {
if i % 2 == 0 {
*even.entry(c).or_default() += 1;
} else {
*odd.entry(c).or_default() += 1;
}
}
Count { even, odd }
}
}
impl Solution {
fn num_special_equiv_groups(a: Vec<String>) -> i32 {
let mut hs: HashSet<Count> = HashSet::new();
for s in a {
hs.insert(Count::new(s));
}
hs.len() as i32
}
}
#[test]
fn test() {
let a: Vec<String> = vec_string!["a", "b", "c", "a", "c", "c"];
assert_eq!(Solution::num_special_equiv_groups(a), 3);
let a: Vec<String> = vec_string!["aa", "bb", "ab", "ba"];
assert_eq!(Solution::num_special_equiv_groups(a), 4);
let a: Vec<String> = vec_string!["abc", "acb", "bac", "bca", "cab", "cba"];
assert_eq!(Solution::num_special_equiv_groups(a), 3);
let a: Vec<String> = vec_string!["abcd", "cdab", "adcb", "cbad"];
assert_eq!(Solution::num_special_equiv_groups(a), 1);
}
// Accepted solution for LeetCode #893: Groups of Special-Equivalent Strings
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #893: Groups of Special-Equivalent Strings
// class Solution {
// public int numSpecialEquivGroups(String[] words) {
// Set<String> s = new HashSet<>();
// for (String word : words) {
// s.add(convert(word));
// }
// return s.size();
// }
//
// private String convert(String word) {
// List<Character> a = new ArrayList<>();
// List<Character> b = new ArrayList<>();
// for (int i = 0; i < word.length(); ++i) {
// char ch = word.charAt(i);
// if (i % 2 == 0) {
// a.add(ch);
// } else {
// b.add(ch);
// }
// }
// Collections.sort(a);
// Collections.sort(b);
// StringBuilder sb = new StringBuilder();
// for (char c : a) {
// sb.append(c);
// }
// for (char c : b) {
// sb.append(c);
// }
// return sb.toString();
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.