Shortest Impossible Sequence of Rolls - Problem

You are given an integer array rolls of length n and an integer k. You roll a k-sided dice numbered from 1 to k, n times, where the result of the i-th roll is rolls[i].

Return the length of the shortest sequence of rolls so that there's no such subsequence in rolls.

A sequence of rolls of length len is the result of rolling a k-sided dice len times.

Input & Output

Example 1 — Basic Case
$ Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4
Output: 2
💡 Note: We can form any sequence of length 1: [1], [2], [3], [4] all appear in rolls. For length 2, we need all possible pairs, but [1,1] never appears as a subsequence, so answer is 2.
Example 2 — Immediate Missing
$ Input: rolls = [1,1,2,2], k = 4
Output: 1
💡 Note: Values 3 and 4 never appear in rolls, so sequences [3] and [4] are impossible. The shortest impossible sequence has length 1.
Example 3 — Longer Sequence
$ Input: rolls = [1,1,1,2,2,2,3,3,3], k = 3
Output: 2
💡 Note: All length 1 sequences appear: [1], [2], [3]. But some length 2 sequences like [1,2] don't appear as subsequences, so answer is 2.

Constraints

  • 1 ≤ rolls.length ≤ 105
  • 1 ≤ rolls[i], k ≤ 105

Visualization

Tap to expand
Shortest Impossible Sequence of Rolls INPUT rolls array (n=9): 4 2 1 2 3 3 2 4 1 0 1 2 3 4 5 6 7 8 k = 4 Dice values: 1, 2, 3, 4 1 2 3 4 Find shortest sequence NOT a subsequence of rolls ALGORITHM STEPS 1 Initialize Track seen values, count=1 2 Scan Array Add each roll to seen set 3 Check Complete If seen all k values: count++ 4 Reset and Repeat Clear set, continue scan Greedy Trace: Index Seen Set Count 0-2 {4,2,1} 1 3-4 {4,2,1,3} 1-->2 5-8 {3,2,4,1} 2-->3 2 complete sets found Answer = count = 2 FINAL RESULT Shortest impossible sequence: 2 Length = 2 Why length 2? All length-1 sequences (1,2,3,4) exist in rolls But some length-2 missing! Example missing: [4,4] [1,4] Not found as subsequence Output: 2 [OK] Key Insight: Each time we see all k different values, we can form one more "layer" of any sequence. After seeing m complete sets of {1,2,...,k}, all sequences of length m exist as subsequences. The answer is (number of complete sets + 1), as we cannot form all sequences of that length. TutorialsPoint - Shortest Impossible Sequence of Rolls | Greedy Approach
Asked in
Google 15 Amazon 12 Microsoft 8
12.0K Views
Medium Frequency
~25 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen