Solution #
Each element {x,i}
in the stack represents a consecutive group of dominos such that if one domino can reach x
, all the dominos starting from the i-th position until the next group will fall. So when we move to a new domino, we should firstly pop out all the domino that within the reach of the current domino. Then the top domino would be the closest domino that won’t fall if we pull of the current domino, i.e. the answer for the current domino.