I'm quite new to python and algorithm and I encountered a question which is defined as follows:
Suppose that you are given a python list l
of size n
which contains only numbers. We index l
from 0 to n-1
. Further, we suppose that there exists an index k ∈ {1, ..., n-2}
such that
- for all
i ∈ {0, ..., k-1}
,l[i] < l[i+1]
- for all
i ∈ {k, ..., n-2}
,l[i] > l[i+1]
In other words, l is unimodal. An example with k=3
is given below:
l = [-5, 8, 12, 15, 13, 12, 10, 5, 1, 0, -2]
I can easily implement it using an iterative approach:
def findK(l):
k = 0
while l[k] < l[k + 1]:
k += 1
return k
But how can I do it using a recursive way which is O(logn)?