Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding sum of a sorted array in O(log n) Time Complexity

There is a Sorted Array A[1,..,n] where each element in the array is between [0-9] and numbers can be repeated with conditions i.e. A[i] <= A[i+1] (less than equal to)

Is there any way to compute this in O(log n) time complexity?

like image 744
Hey.Its_RJ Avatar asked Sep 16 '25 17:09

Hey.Its_RJ


1 Answers

Use binary search to find the first occurrence of 0, then the first occurrence of 1, and so on all the way up to 9. That way, you'll know the exact count of 0's, 1's, 2's.. etc in the array.

Array sum = (1's count*1) + (2's count * 2) ... (9's count * 9).

Total complexity = O(logN) for running binary search 9 times.

Edit:

Count of x in the array will be

If `x` isn't the largest element
count(x) = (first index of the next greatest number) - (first index of x)

Else
count(x) = length of array - (first index of x)
like image 115
Abhinav Mathur Avatar answered Sep 19 '25 07:09

Abhinav Mathur