HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Finding a '1' cell with a '0' to its right in a binary array

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
cellwitharrayitsbinaryfindingright

Problem

Given an array of size n that holds ones and zeros I need to find an index of a 1 cell that has 0 to his right (in then next cell) there could be more than one pair in a given array, any one of them is fine. The array is not sorted, but we do know that the first element is 1 and the last element is 0.

The search should be in $O(\log n)$ time. I'm thinking that a binary search variation is the answer but I'm not sure how.

Solution

After viewing the original question, it seems that you have an additional piece of information: you know that the first element is 1 and that the last element is 0.
This is crucial!

So indeed you can solve it with binary search: first observe that if the first element is 1 and the last is 0, there must be subsequence of the form $1,0$ in the array.

Denote the array by $A[1,...,n]$. If $A[n/2]=1$, then there is a $1,0$-subsequence in the subarray $A[n/2,...,n]$. If $A[n/2]=0$, then there is a $1,0$-subsequence in the subarray $A[1,...,n/2]$.

So you can use Binary search, which takes $O(\log n)$ time.

Context

StackExchange Computer Science Q#9969, answer score: 7

Revisions (0)

No revisions yet.