FastPrepShortest Subarray With at Least K Distinct Values

Shortest Subarray With at Least K Distinct Values

Google logoGoogle● MediumNEW GRADINTERNONSITE INTERVIEW
Learn

Problem statement

Given an integer array nums and a positive integer k, return the minimum length of a contiguous subarray containing at least k distinct values.

Return -1 when no such subarray exists.

Function

shortestSubarrayAtLeastKDistinct(nums: int[], k: int) → int

Examples

Example 1

nums = [1,2,1,3,4]k = 3return = 3

Subarray [2,1,3] has three distinct values and no length-two subarray can.

Example 2

nums = [1,1,1]k = 2return = -1

The entire array contains only one distinct value.

Example 3

nums = [5,6]k = 1return = 1

Any single element already contains one distinct value.

Constraints

  • 1 <= nums.length <= 200000.
  • 1 <= k <= nums.length.
  • -1000000000 <= nums[i] <= 1000000000.

More Google problems

See Google hiring insights
public int shortestSubarrayAtLeastKDistinct(int[] nums, int k) {
    // Write your code here.
}
nums[1,2,1,3,4]
k3
expected3
Checking account…