VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-subarrays-total-distinct-elements-original-array/

⇱ Count Full Distinct Subarrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Full Distinct Subarrays

Last Updated : 14 Mar, 2026

Given an array arr[] consisting of integers, find the number of subarrays of arr[] that contain exactly the same number of distinct elements as the entire array.

Examples:

Input: arr[] = [1, 2, 1, 3]
Output: 2
Explanation: The array has 3 distinct elements. Subarrays with exactly 3 distinct elements are:
[1, 2, 1, 3], [2, 1, 3]

Input: arr[] = [4, 3, 4, 3, 5]
Output: 3
Explanation: The array has 3 distinct elements. Subarrays with exactly 3 distinct elements are:
[4, 3, 4, 3, 5], [3, 4, 3, 5], [4, 3, 5]

[Naive Approach] Subarray Traversal with Hashing - O(n^2) Time and O(n) Space

  • Traverse all possible subarrays of the array.
  • For each subarray, use a hash set to store elements and count the number of distinct elements.
  • If the count of distinct elements equals the total distinct elements in the original array, increase the answer count.

Output
2

[Expected Approach] Sliding Window with Hashing - O(n) Time and O(n) Space

  • Use a sliding window with two pointers l (start) and r (end) to maintain a dynamic subarray.
  • Maintain a hash map to store the distinct elements currently present in the window.
  • Fix the starting index l and expand r until the window [l, r] contains all distinct elements of the array.
  • Once the window becomes valid, all larger windows [l, r+1], [l, r+2] ... will also remain valid, so count all such subarrays together. Then move l forward, update the hash map accordingly, and repeat the process for the next window.

Output
2


Comment
Article Tags: