How to find the time complexity?

Given an array A that has elements from the index 0 to N-1 are negative and from the index N to M-1 are positive. How do you find an algorithm that finds N in O(lg n) time complexity?

  • Consider a Array A of size M.  A[0], A[1], A[2], ......,A[n-1],A[n],A[n+1],......,A[M-1]. Elements A[0],...........,A[N] are negative and A[n+1],..........,A[M-1] are positive .What is the  O(lg N) algorithm that find the position N. Input : A[],M Output : N O(lg M) is obvious , but we need O(lg N).

  • Answer:

    Simple. Check numbers of the form 2^k -1. On finding the 1st positive number, So a modified binary search. It takes approx 2 log(N) time.

Kunal Tyagi at Quora Visit the source

Was this solution helpful to you?

Other answers

Assume the first N elements to form a binary tree. (Binary tree represented as array . Root is A[0] , for every node i , left child is A[i*2+1] and right child is A[i*2+2].)  Start at the root and proceed to the right each time, till you encounter a positive element. Let the num of levels traversed be 'L', and the current index be 'r' (r > N). Again start at the root and proceed to the left each time, for exactly 'L' levels, and let the current index be 'l'. If the value at 'l' is positive, then N=l-1. Else, perform a binary search between the indices 'l' and 'r'. Since 'L' can max be ceil(log N), so determining 'l' and 'r' takes O(log N) time. Further, 'r' - 'l' can max be N+2, so binary search will further take O(log N) time. So, overall time complexity - O(log N)..

Vignesh Raghuraman

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.