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
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:
- Can I do a Master Boot Record fix with a Knoppix 6.1 CD? And How?Best solution by Super User
- How can I find out the time of sunrise?Best solution by Yahoo! Answers
- How do i find a profile of a person with a yahoo mail address?Best solution by Yahoo! Answers
- How do I find out if I'm eligible for Medicaid?Best solution by Yahoo! Answers
- How can I find out what tax code I'm on?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.