
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Subarrays with K Different Integers in C++
Suppose we have an array A of positive integers, we can call a good subarray (contiguous) of A, if the number of different integers in that subarray is exactly K. So, if the array is like [1,2,3,1,2] has 3 different integers: 1, 2, and 3. We have to find the number of good subarrays of A.
So, if the input is like [1,2,3,1,4] and K = 3, then the output will be 4, as it can form three subarrays with exactly four distinct integers, these are [1,2,3], [1,2,3,1], [2,3,1], [3,1,4].
To solve this, we will follow these steps −
Define a function atMost(), this will take an array a and variable k,
Define one set current
j := 0, ans := 0, n := size of a
Define one map m
-
for initialize i := 0, when i < size of a, update (increase i by 1), do −
-
if m[a[i]] is zero, increase m[a[i]] by 1 then −
-
while k < 0, do −
-
if decrease m[a[j]] by 1 and m[a[i]] is zero, then −
(increase k by 1)
(increase j by 1)
-
-
x := ((i - j) + 1)
ans := ans + x
-
return ans
From the main method do the following −
return atMost(a, k) - atMost(a, k - 1);
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int subarraysWithKDistinct(vector<int>& a, int k) { return atMost(a, k) - atMost(a, k - 1); } int atMost(vector <int>& a, int k){ set <int> current; int j = 0; int ans = 0; int n = a.size(); unordered_map <int, int> m; for(int i = 0; i < a.size(); i++){ if(!m[a[i]]++) k--; while(k < 0){ if(!--m[a[j]]) k++; j++; } int x = ((i - j) + 1); ans += x; } return ans; } }; main(){ Solution ob; vector<int> v = {1,2,3,1,4}; cout << (ob.subarraysWithKDistinct(v, 3)); }
Input
{1,2,3,1,4}, 3
Output
4