![]() |
VOOZH | about |
Given an array where each element is a vector containing integers in sorted order. The task is to answer following queries:
count(start, end, k) : Count the numbers smaller than or equal to k in range from array index 'start' to 'end'.
For convenience we consider an n * n 2-D array where each row corresponds to an integer vector. Examples:
Input : ar[][] = {{2, 4, 5},
{3, 4, 9},
{6, 8, 10}}
Queries[] = (0, 1, 5)
(1, 2, 1)
(0, 2, 6)
Output : 5
0
6
Count of elements (smaller than or equal to 5) from
1st row (index 0) to 2nd row (index 1) is 5.
Count of elements (smaller than or equal to 1) from
2nd row to 3nd row is 0
Count of elements (smaller than or equal to 6) from
1st row to 3nd row is 6.
The key idea is to build a Segment Tree with a vector at every node and the vector contains all the elements of the sub-range in a sorted order. And if we observe this segment tree structure this is somewhat similar to the tree formed during the merge sort algorithm(that is why it is called merge sort tree)
5 0 6
buildTree() analysis : Build a merge sort tree takes O(N log N) time which is same as Merge Sort Algorithm. It also takes O(n log n) extra space. query() analysis : A range 'start' to 'end' can divided into at most Log(n) parts, where we will perform binary search on each part . Binary search requires O(Log n). Therefore total complexity O(Log n * Log n).
The space complexity of the program is O(n log n) since the segment tree is constructed using an array of vectors with a maximum size of n log n.