Problem solution · Python

Frequencies of Shortest Supersequences

Frequencies of Shortest Supersequences: a Python solution using sorting and greedy selection. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sorting and greedy selection
Source
walkccc LeetCode Solutions
Length
75 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Choose the key that reveals the greedy or grouping structure.
  2. Sort the relevant records by that key.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFrequencies of Shortest Supersequences · PythonPython
Use this to learn the idea, then write your own version.
from enum import Enum  class State(Enum):  INIT = 0  VISITING = 1  VISITED = 2  class Solution:  def supersequences(self, words: list[str]) -> list[list[int]]:    ans = []    edges = [(string.ascii_lowercase.index(words[0]),              string.ascii_lowercase.index(words[1]))             for words in words]    nodes = sorted({u for u, _ in edges} | {v for _, v in edges})    letterToIndex = {letter: i for i, letter in enumerate(nodes)}    graph = [[] for _ in range(len(nodes))]     for u, v in edges:      graph[letterToIndex[u]].append(letterToIndex[v])     for doubledSubset in self._getMinimumSubsets(graph):      freq = [0] * 26      for letter in nodes:        freq[letter] = 1      for index in doubledSubset:        freq[nodes[index]] = 2      ans.append(freq)     return ans   def _getMinimumSubsets(self, graph: list[list[int]]) -> list[tuple[int]]:    """    Returns a list of the minimum subsets of nodes that do not create a cycle    when skipped.    """    n = len(graph)    for subsetSize in range(n + 1):      doubleSubsets = []      for doubledSubset in itertools.combinations(range(n), subsetSize):        if not self._hasCycleSkipping(graph, set(doubledSubset)):          doubleSubsets.append(doubledSubset)      if doubleSubsets:        return doubleSubsets    return []   def _hasCycleSkipping(      self,      graph: list[list[int]],      doubledSubset: set[int]  ) -> bool:    """    Returns True if there is a cycle in the `graph` when skipping any edges    whose both endpoints are in `doubledSubset`.    """    states = [State.INIT] * len(graph)     def hasCycle(u: int) -> bool:      if states[u] == State.VISITING:        return True      if states[u] == State.VISITED:        return False      states[u] = State.VISITING      if u not in doubledSubset:        for v in graph[u]:          if v in doubledSubset:            continue          if hasCycle(v):            return True      states[u] = State.VISITED      return False     return any(hasCycle(i) for i in range(len(graph))) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗