there was a question in the exam as below:
Let we have a sorted array consisting of $n$-many positive integers. Write a code that checks whether $k^{th}$ term is $k$ or not which takes $O(\log n)$ to run.
Even if I know that it will take much more time than $O(\log n)$, I wrote a code in Magma CAS language. First, I said that the array we have is $A$ and created a new array $B$ such that $B[i]=A[i]-i$. Then for $i \in {1,\dots, n}$ I run the code to check whether $B[i]==0$ or not.
How can we write such a code with computing time $O(\log n)$? Thanks.
If you are allowed to have the same number appear multiple times (necessarily consecutively) in the array, then it's impossible to do in $O(\log n)$ time.
Hint: I am assuming the same number cannot appear twice, and that what you want your algorithm to check is "is
A[k] == kfor allk?"Then see what you can get out of the fact that the array is a sorted array containing only positive numbers, and think about how $O(\log n)$ algorithms usually work: By repeatedly splitting in half and discarding one part. Also, forget your
Barray, as simply creating it takes $O(n)$ time.