1291. Cut Out to Simplify

A shelf holds a row of labelled boxes, given as the array nums, and a tidy shelf may show at most k different labels. You may take out exactly one contiguous run of boxes; the run may be empty or the whole row. The boxes left behind keep their order. Return the smallest number of boxes you must take out so that the remaining boxes show at most k different labels. If the row already qualifies, the answer is 0, and if k is 0 you must remove everything.

Aim for O(n) time and O(n) space, where n is the length of nums: keep a prefix and a suffix in one shared count map and move the two boundaries only forward.

Example 1

Input:
nums = [1,2,3,1,2], k = 2
Output:
1
Explanation:

Removing the single box labelled 3 leaves 1, 2, 1, 2 with only two different labels, so 1 box is enough.

Example 2

Input:
nums = [4,4,4], k = 1
Output:
0
Explanation:

The row already shows one label, which is at most k = 1, so nothing needs to be removed.

Example 3

Input:
nums = [1,2,3,4,1], k = 1
Output:
3
Explanation:

Keeping the first 1 and the last 1 means removing the middle run 2, 3, 4, which is 3 boxes.

Constraints

1 ≤ nums.length ≤ 2 * 105

1 ≤ nums[i] ≤ 109

0 ≤ k ≤ nums.length

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…