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 lowercasetyped:- If
typedis exactly a command, return it. - Otherwise, if exactly one command starts with
typed, return that command. - Otherwise return
None.
- If
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.