Problem Description
Given an integer array rolls of length n and an integer k representing a k-sided dice (numbered from 1 to k), determine the length of the shortest sequence of dice rolls such that this sequence is not a subsequence of rolls. A sequence of rolls of length len is defined as the outcome of rolling the dice len times.
Key Insights
- Instead of checking every possible sequence (which is exponential in possibilities), we can use a greedy strategy.
- We simulate rolling by scanning through rolls and "collecting" one complete set of numbers from 1 to k.
- Every time we collect all k numbers, it indicates we can form all sequences up to that complete round.
- The answer is the count of complete rounds we have accumulated plus one additional roll (which will create a sequence that is impossible to form).
Space and Time Complexity
Time Complexity: O(n) – We traverse the rolls array once. Space Complexity: O(k) – We maintain a boolean array or equivalent structure to track k numbers.
Solution
The solution uses a greedy approach where we iterate over the rolls array keeping track of numbers seen in the current round. A complete round is when we have seen every number in the range [1, k]. We then reset our tracker to simulate a new round. The number of complete rounds we have, plus one, gives the shortest sequence length that cannot be formed as a subsequence. The key idea is that each complete round allows us to represent all sequences of that length, so the next length becomes impossible.