[InterviewBit] Order of People Heights

Order of People Heights

  • Time : O(nlogn + nloglogn)
  • 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
int query(vector<int>& fenwick, int n) {
int res = 0;
while(n) {
res += fenwick[n];
n -= n & -n;
}
return res;
}

void update(vector<int>& fenwick, int n, int MAX_N) {
while(n < MAX_N) {
fenwick[n] += 1;
n += n & -n;
}
}

int helper(int n, vector<int>& fenwick, int MAX_N) {
int l = 1, r = MAX_N;
while(l <= r) {
int m = l + (r - l) / 2;
int rem = m - query(fenwick, m);
if(rem <= n) l = m + 1;
else r = m - 1;
}
return l;
}

vector<int> Solution::order(vector<int> &A, vector<int> &B) {
int n = A.size();
vector<pair<int, int>> C;
vector<int> res(n);
vector<int> fenwick(n + 1);
for(int i = 0; i < n; i++) C.push_back({A[i],B[i]});
sort(begin(C), end(C));
for(auto& [h,seq] : C) {
int idx = helper(seq, fenwick, n + 1);
res[idx - 1] = h;
update(fenwick, idx, n + 1);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/05/PS/interviewbit/order-of-people-heights/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.