Dsa
Sliding Window
Medium
Count Distinct Elements in Sliding Window
You are given an integer array `arr` and an integer `k`. Your task is to count the number of distinct elements in every contiguous subarray of size `k`. If the array is empty or k is larger than the length of the array, return an empty list.
Input Format:
- The first line contains two integers n (1 <= n <= 10^5) and k (1 <= k <= n).
- The second line contains n space-separated integers representing the elements of the array.
Output Format:
- Print a list of integers where each integer represents the count of distinct elements in the respective subarray of size `k`.
Example:
Input:
5 3
1 2 1 2 3
Output:
2 2 3
Key concepts
sliding_windowhashmapsets
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now