This is a classic sliding window + hashmap frequency problem

Problem Summary

In this problem, you are given:

Your task is to find:

In simple words, you need to move a window of size k across the array and, for each position, count how many unique elements are present in that window.

Key Insight

Instead of recalculating distinct elements for every window from scratch, which would be inefficient, we use an optimized approach:

This allows us to efficiently track how many distinct elements exist in the current window at any moment.

Idea

The main idea is to dynamically maintain the count of elements as the window moves.

Instead of recomputing everything:

At any point, the size of the HashMap represents the number of distinct elements in the current window.

Algorithm

Step 1: Build the First Window

Step 2: Slide the Window

Now move the window one element at a time from left to right.

For each new index i:

Example

Input:

arr = [1, 2, 1, 3, 4, 2, 3], k = 4

Windows and distinct counts:

Output:

[3, 4, 4, 3]

Java Solution

import java.util.*;

class Solution {
    ArrayList<Integer> countDistinct(int arr[], int k) {

        ArrayList<Integer> result = new ArrayList<>();
        HashMap<Integer, Integer> map = new HashMap<>();

        int n = arr.length;

        // first window
        for (int i = 0; i < k; i++) {
            map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
        }

        result.add(map.size());

        // sliding window
        for (int i = k; i < n; i++) {

            // add new element
            map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);

            // remove old element
            int old = arr[i - k];

            map.put(old, map.get(old) - 1);

            if (map.get(old) == 0) {
                map.remove(old);
            }

            result.add(map.size());
        }

        return result;
    }
}

Complexity

Key Takeaways

Pattern Recognition

If you encounter problems with:

You should think of:

Summary

This problem is a standard example of combining the sliding window technique with a HashMap to efficiently track the number of distinct elements in a fixed-size subarray. By updating the frequency map dynamically as the window moves, we avoid redundant computations and achieve optimal performance. This approach is widely used in coding interviews and real-world scenarios involving continuous data processing and window-based analysis.