Skip to the code
cf.
+25 XP

#437 Fewest Reversed Links

medium

A wizard-style form has n steps numbered 0 to n - 1. Each links[i] = [a, b] is a "Next" button that goes from step a to step b. Going from b back to a along that same link is possible with the "Back" button, but product wants to count how often users must go backwards.

Write fewestBacks(n, links) that returns the fewest "Back" moves on any route from step 0 to step n - 1, where following a link forward is free and following it backward costs 1. Return -1 if step n - 1 can't be reached even using links backward.

Example 1

Input: n = 4, links = [[0,1],[2,1],[2,3]]
Output: 1

Go 0 → 1 forward, then 1 → 2 against the link [2, 1] (cost 1), then 2 → 3 forward.

Example 2

Input: n = 3, links = [[1,0],[2,1]]
Output: 2

Both links point toward step 0, so both must be used backward.

Constraints

  • 1 <= n <= 10000
  • 0 <= links.length <= 50000
  • 0 <= a, b < n
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).