We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Shortest Impossible Sequence of Rolls

Number: 2435

Difficulty: Hard

Paid? No

Companies: Google


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.


Code Solutions

# Python solution with detailed comments
class Solution:
    def shortestSequence(self, rolls: List[int], k: int) -> int:
        # tracks the number of complete rounds
        rounds_completed = 0
        # counts distinct numbers seen in the current round
        distinct_count = 0
        # boolean list to track if a number has been seen in the current round (index 1 to k)
        seen = [False] * (k + 1)
        
        # Iterate through each roll encountered
        for roll in rolls:
            # If roll hasn't been seen in this round, mark it and update count
            if not seen[roll]:
                seen[roll] = True
                distinct_count += 1
                # If we have seen all numbers from 1 to k, one complete round is finished
                if distinct_count == k:
                    rounds_completed += 1
                    # reset for a new round
                    distinct_count = 0
                    seen = [False] * (k + 1)
        # The answer is one more than the complete rounds
        return rounds_completed + 1
← Back to All Questions