Skip to the code
+50 XP

#417 Every Route to Checkout

hard

A store's analytics team wants every click path a shopper could take from the landing page to checkout. Pages are numbered 0 to n - 1, where n = pages.length. pages[i] lists the pages that page i links to. Page 0 is the landing page and page n - 1 is checkout. The links never form a loop, and checkout links nowhere.

Many pages never lead to checkout, like help articles that only link to more help articles. A store has up to 100 pages and at most 10,000 routes reach checkout, but the paths that wander into dead ends can number in the quadrillions, so walking all of them is far too slow.

Write allRoutes(pages) that returns every path from page 0 to page n - 1, each as a list of page numbers. Sort the paths in lexicographic order: compare two paths page by page, and the path with the smaller page at the first difference comes first.

Example 1

Input: pages = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]

Page 0 leads to 1 and 2, and both lead to checkout (page 3).

Example 2

Input: pages = [[2,1],[2],[]]
Output: [[0,1,2],[0,2]]

[0, 1, 2] comes first because at the second position 1 is smaller than 2.

Constraints

  • 2 <= pages.length <= 100
  • The links form no loop.
  • pages[n - 1] is empty.
  • At most 10,000 routes lead from page 0 to page n - 1.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

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