#3435

Frequencies of Shortest Supersequences

Hard
ArrayStringBit ManipulationGraph TheoryTopological SortEnumeration
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute-force approach generates all possible combinations of characters from the input strings and checks if they can form a valid supersequence. This method is straightforward but inefficient due to the exponential growth of combinations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate all possible combinations of characters from the input strings, allowing each character to appear at most twice.
  2. 2Step 2: For each combination, check if it contains all input strings as subsequences.
  3. 3Step 3: If valid, calculate the frequency of each character and store it in the result.
solution.py13 lines
1from itertools import combinations
2
3def get_frequencies(words):
4    freq_set = set()
5    for chars in combinations(set(''.join(words)), 2):
6        for count in range(1, 3):
7            candidate = ''.join(c * count for c in chars)
8            if all(word in candidate for word in words):
9                freq = [0] * 26
10                for c in candidate:
11                    freq[ord(c) - ord('a')] += 1
12                freq_set.add(tuple(freq))
13    return [list(freq) for freq in freq_set]

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.