Skip to the code
cf.
+25 XP

#538 Closest Command Suggestion

medium

A command-line tool in the browser shows "did you mean" when you mistype a command. It compares the typed text with every known command in commands and suggests the one with the smallest edit distance (inserts, deletes, and replacements of single characters).

Write closestCommand(typed, commands) that returns that command. If several commands are equally close, return the one that appears first in commands.

Example 1

Input: typed = "brnch", commands = ["branch","bench","patch"]
Output: "branch"

branch (insert a) and bench (replace r with e) are both 1 edit away, and branch comes first.

Example 2

Input: typed = "comit", commands = ["clone","commit","config"]
Output: "commit"

Inserting one m gives commit; the others need more edits.

Constraints

  • 1 <= commands.length <= 100
  • 1 <= typed.length, commands[i].length <= 30
  • All strings are lowercase letters and -.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).