Skip to the code
cf.
+25 XP

#717 Rank Command Palette Results

medium

Rank commands in a command palette. Score a command against the query like this, ignoring case: walk the command's characters from left to right and match each query character at the first place it can go after the previous match (greedy). Each matched character earns 1 point, 2 more if it comes right after the previous matched character, and 3 more if it is the command's first character or follows a space, -, _, or /. If some query character can't be matched, the command is filtered out.

Write rankCommands(query, commands) that returns the matching commands, best first: higher score first, then shorter command first, then in character-code order (as < compares strings). An empty query matches everything with score 0.

Example 1

Input: query = "gco", commands = ["Toggle Comments","Go to Config","Git: Commit"]
Output: ["Git: Commit","Go to Config","Toggle Comments"]

Git: Commit and Go to Config both score 11 (g and c start words, and o follows c), so the shorter one comes first. Toggle Comments scores 8 because its g doesn't start a word.

Example 2

Input: query = "", commands = ["b","a","cc"]
Output: ["a","b","cc"]

With an empty query all score 0, so shorter first, then alphabetical.

Constraints

  • 0 <= query.length <= 50
  • 0 <= commands.length <= 10^4, each up to 100 characters, all different.
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).