Leetcode 893. Groups of Special
You are given an array of strings of the same length words
. A string B
is a special-equivalent of string A
if they can be made equivalent by performing any number of operations as follows:
i
and j
(i < j) such that i
is even and j
is even, and swap the characters at words[i]
and words[j]
.i
and j
(i < j) such that i
is odd and j
is odd, and swap the characters at words[i]
and words[j]
.Two strings A
and B
are special-equivalent if and only if they contain the same characters in the even indices and the same characters in the odd indices.
Return the number of groups of unique special-equivalent strings from the words
array.
Identify Character Set by Index Parity: Separate characters in each string into two sets: characters at even indices and characters at odd indices.
Sort and Form Key: Sort each set and combine them to form a unique key for each string. This key represents the string regardless of swaps allowed by the special-equivalence operations.
Count Unique Keys: Use a set to keep track of unique keys. The size of the set at the end will be the number of unique special-equivalent groups.
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
public class SpecialEquivalentStrings {
public int numSpecialEquivGroups(String[] words) {
Set<String> uniqueKeys = new HashSet<>();
for (String word : words) {
String evenChars = getCharsByIndexParity(word, true);
String oddChars = getCharsByIndexParity(word, false);
String key = evenChars + oddChars;
uniqueKeys.add(key);
}
return uniqueKeys.size();
}
private String getCharsByIndexParity(String word, boolean even) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
if (even && i % 2 == 0) {
sb.append(word.charAt(i));
}
if (!even && i % 2 != 0) {
sb.append(word.charAt(i));
}
}
char[] charArray = sb.toString().toCharArray();
Arrays.sort(charArray);
return new String(charArray);
}
public static void main(String[] args) {
SpecialEquivalentStrings ses = new SpecialEquivalentStrings();
String[] words = {"abc", "acb", "bac", "bca", "cab", "cba"};
System.out.println(ses.numSpecialEquivGroups(words)); // Output: 3
}
}
Total Processing: Since we do this for each string in the array, the total time complexity is O(N * L log L), where N is the number of strings and L is the length of each string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?