The problem:
Let
A = A[1]<=A[2]....A[n]be a sorted array ofnnumbers. Letxbe a number. Design anO(log n)time algorithm to find the number of timesxappears in the array. What is the time complexity.
My answer:
Using a binary search find if x = middle. If x is middle then there is a chance x could appear in left and right side of middle. So create left array L[] and right array R[]. Using binary search find the the first time x appeared in L[]. Do the same thing for R[], but to find the last time x appeared in R[]. Note the indexes. So the number of time x appeared = Lastindex - FirstIndex + 1. Time complexity 2log n + c = O(log n). It's just a 'skeleton part' of algorithm since the answer doesn't have to be elaborated. This is what I found, but is there a better solution?
x, but you never go back to answer for if it isn'tx. 2. There is no reason to create a separate left and right array, just do two binary searches on the original array and find the indexes.