BackmediumHashing

Count Distinct Subarray Elements Solution

Problem Statement

Given an array of integers and an integer k, count the number of subarrays having exactly k distinct elements.

Example 1
Input
[1, 2, 1, 2, 3], k = 2
Output
7

Explanation: Subarrays with 2 distinct elements: [1, 2], [2, 1], [1, 2], [2, 3], [1, 2, 1], [2, 1, 2], [1, 2]

Example 2
Input
[4, 4, 4, 4], k = 1
Output
10

Explanation: Subarrays with 1 distinct element: [4], [4], [4], [4], [4, 4], [4, 4], [4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4, 4]

Constraints

  • 1 <= array length <= 10^5
  • 1 <= k <= min(array length, 10^5)
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free