Since we need to access O (1), the required data structure will be memory intensive.
With a hash table, in the worst case, access will take O (n)
My decision:
Building a 2D matrix.
array = {2,3,2,4,1,4,6} The range of numbers is from 0 to 6, so n = 7
So we have to create the nxn matrix.
array [i] [i] represents the total count of the element = i
therefore array [4] [4] = 2 (since 4 appears in the array 2 times)
array [5] [5] = 0
array [5] [2] = the number of numbers, both> = 2 and <= 5 = 5
//preprocessing stage 1: Would populate a[i][i] with total count of element = i a[n][n]={0}; for(i=0;i<=n;i++){ a[i][i]++; } //stage 2 for(i=1;i<=n;i++) for(j=0;j<i;j++) a[i][j] = a[i-1][j] + a[i][i]; //we are just adding count of element=i to each value in i-1th row and we get ith row.
Now (5.2) will query for [5] [2] and give an answer in O (1)
source share