Skip to content

2350. Shortest Impossible Sequence of Rolls 👍

  • Time: $O(n)$
  • Space: $O(k)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int shortestSequence(vector<int>& rolls, int k) {
    int ans = 1;  // the the next target length
    unordered_set<int> seen;

    for (const int roll : rolls) {
      seen.insert(roll);
      if (seen.size() == k) {
        // Have all combinations that form `ans` length, and we are going to
        // extend the sequence to `ans + 1` length.
        ++ans;
        seen.clear();
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int shortestSequence(int[] rolls, int k) {
    int ans = 1; // the the next target length
    Set<Integer> seen = new HashSet<>();

    for (final int roll : rolls) {
      seen.add(roll);
      if (seen.size() == k) {
        // Have all combinations that form `ans` length, and we are going to
        // extend the sequence to `ans + 1` length.
        ++ans;
        seen.clear();
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def shortestSequence(self, rolls: list[int], k: int) -> int:
    ans = 1  # the the next target length
    seen = set()

    for roll in rolls:
      seen.add(roll)
      if len(seen) == k:
        # Have all combinations that form `ans` length, and we are going to
        # extend the sequence to `ans + 1` length.
        ans += 1
        seen.clear()

    return ans