Imagine you're organizing a three-stage tournament where participants must progress through stages in a specific order: Training (0), Qualifying (1), and Championship (2). A special subsequence represents a valid tournament path that includes at least one participant from each stage, in the correct order.
Given an array nums containing only integers 0, 1, and 2 (representing the three tournament stages), your task is to count how many different subsequences form valid tournament paths.
A special subsequence must follow this pattern:
- Start with one or more 0s (Training stage)
- Follow with one or more 1s (Qualifying stage)
- End with one or more 2s (Championship stage)
Examples of valid paths:
[0,1,2]- Basic path through all stages[0,0,1,1,1,2]- Multiple participants at each stage
Invalid paths:
[2,1,0]- Wrong order[1]- Missing stages[0,1,2,0]- Going backwards
Return the total count modulo 109 + 7 since the answer can be very large.
Input & Output
Visualization
Time & Space Complexity
Single pass through the array with constant work per element
Only three variables needed to track DP states
Constraints
- 1 β€ nums.length β€ 105
- nums[i] β {0, 1, 2}
- Return result modulo 109 + 7