Skip to the code
cf.
+25 XP

#434 Rename a CSS Class One Letter at a Time

medium

A design system is renaming a CSS class from begin to end, but a strict linter only lets each commit change exactly one letter, and every intermediate name must be one of the approved names in allowed. The final name end must also be approved.

Write renameSteps(begin, end, allowed) that returns the fewest commits needed, or -1 if it can't be done. If begin === end, the answer is 0. All names are lowercase letters a to z and have the same length. begin itself doesn't need to be approved.

Example 1

Input: begin = "tabs", end = "tips", allowed = ["tibs","tips","taps","tops"]
Output: 2

For example tabs → taps → tips: two commits, each changing one letter.

Example 2

Input: begin = "link", end = "line", allowed = ["lint","lone"]
Output: -1

line isn't an approved name, so it can never be the final name.

Constraints

  • 1 <= begin.length <= 10
  • 0 <= allowed.length <= 5000
  • All names have the same length.
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).