Problem
You are given an array of strings words
. Find all shortest common supersequences (SCS) of words
that are not permutations of each other.
A shortest common supersequence is a string of minimum length that contains each string in words
as a subsequence.
Return a 2D array of integers freqs
that represent all the SCSs. Each
freqs[i]
is an array of size 26, representing the frequency of each letter in the lowercase English alphabet for a single SCS. You may return the frequency arrays in any order.
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= words.length <= 256
words[i].length == 2
- All strings in
words
will altogether be composed of no more than 16 unique lowercase letters. - All strings in
words
are unique.
Examples
Solution
Method 1 – BFS with State Compression and Topological Search
Intuition
The shortest common supersequence (SCS) problem can be modeled as finding all minimal-length strings that contain all words as subsequences. We can use BFS to explore all possible supersequences, using state compression (bitmask) to avoid redundant work, and topological search to ensure all orderings are considered. For each unique SCS, we count the frequency of each letter.
Approach
- Use BFS to build SCSs by appending characters from any word that matches the current position.
- Represent the state as a tuple of current indices in each word and the current supersequence.
- Use a set to avoid revisiting the same state.
- Stop BFS when the shortest length is reached for all possible SCSs.
- For each unique SCS, count the frequency of each letter and add to the result.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(k^n * L)
wherek
is the alphabet size,n
is the number of words, andL
is the SCS length. The number of states grows exponentially with the number of words. - 🧺 Space complexity:
O(k^n * L)
for storing all possible states and supersequences.