Approach
Sorting and greedy selection
For Frequencies of Shortest Supersequences, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 75 lines of Python from the credited upstream file 3435.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from enum import Enum2 3 4class State(Enum):5 INIT = 06 VISITING = 17 VISITED = 28 9 10class Solution:11 def supersequences(self, words: list[str]) -> list[list[int]]:12 ans = []13 edges = [(string.ascii_lowercase.index(words[0]),14 string.ascii_lowercase.index(words[1]))15 for words in words]16 nodes = sorted({u for u, _ in edges} | {v for _, v in edges})17 letterToIndex = {letter: i for i, letter in enumerate(nodes)}18 graph = [[] for _ in range(len(nodes))]19 20 for u, v in edges:21 graph[letterToIndex[u]].append(letterToIndex[v])22 23 for doubledSubset in self._getMinimumSubsets(graph):24 freq = [0] * 2625 for letter in nodes:26 freq[letter] = 127 for index in doubledSubset:28 freq[nodes[index]] = 229 ans.append(freq)30 31 return ans32 33 def _getMinimumSubsets(self, graph: list[list[int]]) -> list[tuple[int]]:34 """35 Returns a list of the minimum subsets of nodes that do not create a cycle36 when skipped.37 """38 n = len(graph)39 for subsetSize in range(n + 1):40 doubleSubsets = []41 for doubledSubset in itertools.combinations(range(n), subsetSize):42 if not self._hasCycleSkipping(graph, set(doubledSubset)):43 doubleSubsets.append(doubledSubset)44 if doubleSubsets:45 return doubleSubsets46 return []47 48 def _hasCycleSkipping(49 self,50 graph: list[list[int]],51 doubledSubset: set[int]52 ) -> bool:53 """54 Returns True if there is a cycle in the `graph` when skipping any edges55 whose both endpoints are in `doubledSubset`.56 """57 states = [State.INIT] * len(graph)58 59 def hasCycle(u: int) -> bool:60 if states[u] == State.VISITING:61 return True62 if states[u] == State.VISITED:63 return False64 states[u] = State.VISITING65 if u not in doubledSubset:66 for v in graph[u]:67 if v in doubledSubset:68 continue69 if hasCycle(v):70 return True71 states[u] = State.VISITED72 return False73 74 return any(hasCycle(i) for i in range(len(graph)))75