FastPrepChoose Your Own Ending

Choose Your Own Ending

WhatNot logoWhatNot● EasyINTERNPHONE SCREEN
Learn

Problem statement

A branching story has pages numbered from 0 to n - 1. The two integers in nextPages[p] describe page p:

  • [-1,-1] means that page p is a terminal ending.
  • Otherwise, the first integer is the next page for choice 0, and the second is the next page for choice 1.

Start at page 0 and consume the supplied choices in order. Stop as soon as a terminal page is reached and return its page number; ignore any choices left over. If all choices are consumed while the current page is not terminal, return -1.

Pages may form cycles and may be visited repeatedly. The finite choice sequence limits how many transitions are performed; do not search for an ending that the supplied choices do not reach.

Function

chooseEnding(nextPages: int[][], choices: int[]) → int

Examples

Example 1

nextPages = [[1,2],[-1,-1],[1,3],[-1,-1]]choices = [1,1]return = 3

Starting at page 0, the two right choices move to page 2 and then terminal page 3.

Example 2

nextPages = [[1,2],[-1,-1],[1,3],[-1,-1]]choices = [1]return = -1

The only choice reaches page 2, which is not terminal. No choices remain.

Example 3

nextPages = [[-1,-1]]choices = [0,1]return = 0

The starting page is already an ending, so the extra choices are ignored.

Constraints

  • 1 <= nextPages.length <= 50.
  • Every row has exactly two values. A row is either [-1,-1] or contains two valid page numbers from 0 to nextPages.length - 1.
  • 0 <= choices.length <= 200, and every choice is 0 or 1.

More WhatNot problems

See WhatNot hiring insights
public int chooseEnding(int[][] nextPages, int[] choices) {
    // write your code here
}
nextPages[[1,2],[-1,-1],[1,3],[-1,-1]]
choices[1,1]
expected3
Checking account…