oneby7

Sliding Window Counting windows

185. Subarrays with K Different Integers

Hard

You are given an array of integers nums and an integer k. Return the number of subarrays that hold exactly k different values. A value may appear any number of times, so [3,3,8] holds two different values.

A subarray is a contiguous sequence of elements from nums, with at least one element. Two subarrays are different if they start or end at different positions, even when they hold the same values.

Example 1

Input: nums = [4, 9, 4, 4, 7], k = 2

Output: 7

Explanation: Five subarrays hold only 4 and 9: [4,9], [4,9,4], [4,9,4,4], [9,4] and [9,4,4]. Two hold only 4 and 7: [4,7] and [4,4,7].

Example 2

Input: nums = [-1000000000, 7, -1000000000, 7], k = 2

Output: 6

Explanation: The array holds two values, and every subarray with two or more elements holds both. There are 3 such subarrays of length 2, 2 of length 3 and 1 of length 4.

Example 3

Input: nums = [0, 0, -2, -2, -2], k = 1

Output: 9

Explanation: A subarray with one value lies inside a run of equal values. The two 0s give 3 subarrays and the three −2s give 6.

Check your understanding

Work out the answer for this input before you write any code.

nums = [7, 7, 3, 7], k = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ nums.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.