1+ /*
2+ Given array and a number k, k<=n
3+ find count of distinct elements in every window of size k
4+
5+ arr = [10, 20, 20, 10, 30, 40, 10] k=4
6+ op: 2 3 4 3
7+
8+ arr = [10, 10, 10, 10] k=3
9+ op: 1 1
10+
11+ arr = [10, 20, 30, 40] k=3
12+ op: 3 3
13+ */
14+
15+ /*
16+ sol1: O(n-k * k * k) time
17+ Consider starting point of every window
18+ There are total n-k+1 windows
19+ so traverse all windows
20+ for each window, count distinct els
21+ We can see if an element is distinct or not
22+ by having two loops
23+ the outer loop picks and element one by one and the
24+ inner loop checks if same element has ocuured before
25+ */
26+
27+ #include < iostream>
28+ using namespace std ;
29+
30+ void printDistinct (int arr[], int n, int k)
31+ {
32+ for (int i = 0 ; i <= n - k; i++)
33+ {
34+ int count = 0 ;
35+ for (int j = 0 ; j < k; j++)
36+ {
37+ bool flag = false ;
38+ for (int p = 0 ; p < j; p++)
39+ if (arr[i+j] == arr[i+p])
40+ {
41+ flag = true ;
42+ break ;
43+ }
44+ }
45+
46+ cout << count << ' \t ' ;
47+ }
48+ }
49+
50+ /*
51+ sol2: O(n-k + k) = O(n) time, O(k) space
52+ Maintain frequency map of elements present in first window
53+ print siz of freq map
54+ Then traverse the windows,
55+ compute freq map of curr window using freq map of prev window
56+
57+ for(int i = k; i < n; i++)
58+ {
59+ - decrease frequency of arr[i-k]
60+ - if freq of arr[i-k] becomes 0
61+ remove it from map
62+
63+ - if arr[i] is absent in map
64+ insert it
65+ else
66+ increase it's frequency in map
67+
68+ - print size of map
69+ }
70+ */
0 commit comments