algoadvance

Leetcode 893. Groups of Special

Problem Statement

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:

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.

Clarifying Questions

  1. Are all input strings guaranteed to be of the same length?
    • Yes, all strings in the input array are of the same length.
  2. What is the maximum length of the strings and the number of strings in the input array?
    • This isn’t specifically mentioned, but let’s assume reasonable competitive programming limits: the length of each word and the number of words could be up to 1000.
  3. Are there any constraints on the characters in the strings?
    • The characters are lowercase English letters.

Strategy

  1. Identify Character Set by Index Parity: Separate characters in each string into two sets: characters at even indices and characters at odd indices.

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

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

Code

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
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI