[Geeks for Geeks] Count Smaller elements

Count Smaller elements

Given an array Arr of size N containing positive integers. Count number of smaller elements on right side of each array.

  • Time : O(nlogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
struct Seg {
int mi, ma, count;
Seg *l, *r;
Seg(vector<int>& A, int le, int ri) : mi(A[le]), ma(A[ri]), count(0), l(nullptr), r(nullptr){
if(le == ri) return;
int m = le + (ri - le) / 2;
l = new Seg(A, le, m);
r = new Seg(A, m + 1, ri);
}
int query(int s, int e) {
if(mi > e or ma < s) return 0;
if(s <= mi and ma <= e) return count;
return (l ? l->query(s, e) : 0) + (r ? r->query(s, e) : 0);
}
int insert(int n) {
if(mi <= n and n <= ma) {
count++;
if(l) l->insert(n);
if(r) r->insert(n);
}
}
};

class Solution{
Seg* seg;
int mi;
void build(vector<int> A) {
sort(begin(A), end(A));
A.erase(unique(begin(A), end(A)), end(A));
mi = A[0];
seg = new Seg(A, 0, A.size() - 1);
}
public:
vector<int> constructLowerArray(int *arr, int n) {
vector<int> res(n), A;
for(int i = 0; i < n; i++) A.push_back(arr[i]);

build(A);

for(int i = n - 1; i >= 0; i--) {
res[i] = seg->query(mi, A[i] - 1);
seg->insert(A[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/19/PS/GeeksforGeeks/count-smaller-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.