Choose Your Own Ending
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 pagepis a terminal ending.- Otherwise, the first integer is the next page for choice
0, and the second is the next page for choice1.
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[]) → intExamples
Example 1
nextPages = [[1,2],[-1,-1],[1,3],[-1,-1]]choices = [1,1]return = 3Starting 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 = -1The only choice reaches page 2, which is not terminal. No choices remain.
Example 3
nextPages = [[-1,-1]]choices = [0,1]return = 0The 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 from0tonextPages.length - 1. 0 <= choices.length <= 200, and every choice is0or1.