← Home

893. Groups of Special-Equivalent Strings

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
893

The trick here is to name the state correctly, then let the implementation follow. For 893. Groups of Special-Equivalent Strings, the solution in this repository is mainly a greedy solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are numSpecialEquivGroups.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02You are given an array A of strings.
03
04Two strings S and T are special-equivalent if after any number of moves, S == T.
05
06A move consists of choosing two indices i and j with i % 2 == j % 2, and swapping S[i] with S[j].
07
08Now, 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.
09
10Return the number of groups of special-equivalent strings from A.
11
12 
13
14Example 1:
15
16Input: ["a","b","c","a","c","c"]
17Output: 3
18Explanation: 3 groups ["a","a"], ["b"], ["c","c","c"]
19Example 2:
20
21Input: ["aa","bb","ab","ba"]
22Output: 4
23Explanation: 4 groups ["aa"], ["bb"], ["ab"], ["ba"]
24Example 3:
25
26Input: ["abc","acb","bac","bca","cab","cba"]
27Output: 3
28Explanation: 3 groups ["abc","cba"], ["acb","bca"], ["bac","cab"]
29Example 4:
30
31Input: ["abcd","cdab","adcb","cbad"]
32Output: 1
33Explanation: 1 group ["abcd","cdab","adcb","cbad"]
34 
35
36Note:
37
381 <= A.length <= 1000
391 <= A[i].length <= 20
40All A[i] have the same length.
41All A[i] consist of only lowercase letters.
42**/
43
44//Runtime: 8 ms, faster than 73.97% of C++ online submissions for Groups of Special-Equivalent Strings.
45class Solution {
46public:
47    int numSpecialEquivGroups(vector<string>& A) {
48        if(A.size()==0) return 0;
49        
50        vector<string> B;
51        
52        for(int i = 0; i < A.size(); i++){
53            string s;
54            
55            for(int j = 0; j < A[i].size(); j+=2){
56                s.push_back(A[i][j]);
57            }
58            for(int j = 1; j < A[i].size(); j+=2){
59                s.push_back(A[i][j]);
60            }
61            sort(s.begin(), s.begin()+(s.size()+1)/2);
62            sort(s.begin()+(s.size()+1)/2, s.end());
63            B.push_back(s);
64        }
65        sort(B.begin(), B.end());
66        
67        int groups = 1;
68        for(int i = 1; i < B.size(); i++){
69            if(B[i]!=B[i-1]) groups++;
70        }
71        return groups;
72    }
73};
74
75/**
76Approach 1: Counting
77Intuition and Algorithm
78
79Let's try to characterize a special-equivalent string S, by finding a function C so that S≡T⟺C(S)=C(T).
80
81Through swapping, we can permute the even indexed letters, and the odd indexed letters. 
82What characterizes these permutations is the count of the letters: 
83all such permutations have the same count, and different counts have different permutations.
84
85Thus, the function C(S)= (the count of the even indexed letters in S, 
86followed by the count of the odd indexed letters in S) 
87successfully characterizes the equivalence relation.
88
89Afterwards, we count the number of unique C(S) for S∈A.
90
91//Java
92class Solution {
93    public int numSpecialEquivGroups(String[] A) {
94        Set<String> seen = new HashSet();
95        for (String S: A) {
96            int[] count = new int[52];
97            for (int i = 0; i < S.length(); ++i)
98                count[S.charAt(i) - 'a' + 26 * (i % 2)]++;
99            seen.add(Arrays.toString(count));
100        }
101        return seen.size();
102    }
103}
104
105Complexity Analysis
106
107Time Complexity: O(∑_i(A_i).length)
108
109Space Complexity: O(N), where N is the length of A. 
110**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.