progress

~/problems / Tries

Abbreviated shell commands

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A router's console accepts any unambiguous prefix of a command: conf for configure, sh for show. Build the lookup.

Implement class CommandSet:

  • CommandSet(commands: list[str]): the known commands (distinct, lowercase, non-empty). The list may be empty.
  • resolve(typed: str) -> str | None, for a non-empty lowercase typed:
    1. If typed is exactly a command, return it.
    2. Otherwise, if exactly one command starts with typed, return that command.
    3. Otherwise return None.
cs = CommandSet(["show", "shutdown", "set", "configure", "copy"])
cs.resolve("sh")      # None         ("show" and "shutdown": ambiguous)
cs.resolve("shu")     # "shutdown"
cs.resolve("conf")    # "configure"
cs.resolve("set")     # "set"        (exact match)
cs.resolve("c")       # None         ("configure" and "copy")
cs.resolve("reload")  # None

⭐ Bonus: a speed test with 20,000 commands and 20,000 inputs earns a star if resolve costs O(len(typed)) instead of checking startswith against every command.

Show hint

Build a trie where each node remembers how many commands pass through it, whether one ends there, and one command that passes through it.

Topic: Trie. Prefix tree; longest-match tokenizing.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc