From a1c1695ab55f52deb9c46751111aea58b525ec96 Mon Sep 17 00:00:00 2001 From: Nitin Rajpoot Date: Tue, 28 Oct 2025 16:19:45 +0530 Subject: [PATCH] Add solution for distinct values subarrays II --- .../distinct_values_subarrays_II.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 2_sorting_searching/distinct_values_subarrays_II.cpp diff --git a/2_sorting_searching/distinct_values_subarrays_II.cpp b/2_sorting_searching/distinct_values_subarrays_II.cpp new file mode 100644 index 0000000..6892ac3 --- /dev/null +++ b/2_sorting_searching/distinct_values_subarrays_II.cpp @@ -0,0 +1,45 @@ +// Problem: Distinct Values Subarrays II +// Category: Sorting and Searching +// Difficulty: Medium +// Time Complexity: O(n) +// Space Complexity: O(n) + +// Approach: +// Use a sliding window [l, r] to maintain at most k distinct elements. +// Track frequencies using a hash map. +// Expand r, and when distinct elements exceed k, move l forward. +// For each r, add (r - l + 1) to the answer (all valid subarrays ending at r). + +#include +using namespace std; + +int main() { + ios::sync_with_stdio(false); + cin.tie(nullptr); + + int n, k; + cin >> n >> k; + vector a(n); + for (int i = 0; i < n; i++) cin >> a[i]; + + long long ans = 0; + unordered_map freq; + int left = 0; + int distinct = 0; + + for (int right = 0; right < n; right++) { + if (freq[a[right]] == 0) distinct++; + freq[a[right]]++; + + while (distinct > k) { + freq[a[left]]--; + if (freq[a[left]] == 0) distinct--; + left++; + } + + ans += (right - left + 1); + } + + cout << ans << "\n"; + return 0; +}