Given a list of distinct integers (decreasing order), return True if there is atleast position p, such that the value at position p is p. For instance, List = [4, 3, 2, 0], the function returns true since 2 is at index 2.
I know we can just go for a loop and check if list[i] == i.
I was wondering if and how this can be implemented with the divide and conquer algorithm?
My base cases are:
- L is empty, return False.
- If L[0] is negative, return False. Since list is in decreasing order, all values will be negative, and all index are positive. SO we will not get a match. For simplicity, i am just considering positive index.
I am a bit confused how to divide the list here. Since splitting the list in 2, each list would have index [0:n/2]. So comparing the the values and index dont make sense.
Appreciate some help!
Advertisement
Answer
You only need to compare the starting and ending values of a list to the values in the list index to see if it’s possible.
Code
JavaScript
x
20
20
1
def divide_conqueer(lst, indexes = None):
2
3
if indexes is None:
4
indexes = list(range(len(lst))) # create list index
5
6
if not lst:
7
return False
8
elif len(lst) == 1:
9
return lst[0] == indexes[0]
10
elif lst[0] < indexes[0] or lst[-1] > indexes[-1]:
11
# Compare values of beginning and end of the list to the
12
# list indexes of the beginnning and end
13
# There is a matching value to index only if beginning value >= starting index and
14
# ending value <= ending index
15
return False
16
else:
17
# Divide values and intervals in half and test each half
18
return (divide_conqueer(lst[:len(lst)//2], indexes[:len(indexes)//2]) or
19
divide_conqueer(lst[len(lst)//2:], indexes[len(indexes)//2:]))
20
Test
JavaScript
1
3
1
print(divide_conqueer([4, 3, 2, 1]))
2
# Output: True
3