Search in unsorted array in logarithmic time

I am currently studying an introduction test to algorithms, and I came across a question that I cannot solve, the question is: you have an array of n integers, the first m elements are even and the rest elements are odd. You need to write an algorithm that finds the value m (finds the index of the last even number) and has a time complexity of O (log m).

I was thinking of doing something similar to binary search and just moving left if odd and moving right if even until I find an even index and its next will be odd, but this thing will work on O (log n) and not O (log m).

+4
source share
1 answer

Start at index 1, then continue doubling the index until you find the odd entry. This gives an upper bound for m over time O (log m). Then do a binary search.

+5
source

Source: https://habr.com/ru/post/1337752/


All Articles