Press "Enter" to skip to content

Posts tagged as “signature”

花花酱 LeetCode 893. Groups of Special-Equivalent Strings

Problem

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
Explanation: 1 group ["abcd","cdab","adcb","cbad"]

Note:

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

Ā 

Solution: Signature

All Special-Equivalent Strings should have the same signature if we sort all the odd-index characters and all the even-index characters.

E.g.Ā [“abcd”,”cdab”,”adcb”,”cbad”] are all in the same graph.

“abcd”: odd “ac”, even: “bd”
“cdab”: odd “ac”, even: “bd”
“adcb”: odd “ac”, even: “bd”
“cbad”: odd “ac”, even: “bd”

We can concatenate the odd and even strings to create a hashable signature.

Time complexity: O(n)

Space complexity: O(n)

C++

Java

Python

Python (1-linear)