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.
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.
Input: n = 3, links = [[1,0],[2,1]] Output: 2
Both links point toward step 0, so both must be used backward.
1 <= n <= 100000 <= links.length <= 500000 <= a, b < nRun 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).
I'm here to help with #437 Fewest Reversed Links. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.