Mysterious Function

Chris received the following algorithm written in Python :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def mysterious(L,i,j):
    if i + 1 == j:
        return -INF

    mid = (i + j) / 2

    x = max(L[i:mid])
    y = max(L[mid:j])
    if x == y:
        return x

    if x > y:
        return max(mysterious(L,i,mid),y)
    else:
        return max(mysterious(L,mid,j),x)

It takes in an integer list L L and initially i = 0 i=0 and j = len ( L ) > 1 j=\text{len}(L) > 1 . What does this algorithm returns?

Details and Assumptions

  • Assume that INF is larger than any integer in L L .
The third maximum number in L L The maximum number in L L None of these choices The third smallest number in L L The smallest number in L L The second smallest number in L L The second maximum number in L L

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

First Last
Aug 1, 2017

Running through the code:

Line 2: If there is now only 1 item in L, return a very small number

Line 7+8: Get the maximum number in each side of the list L

Line 9: If there are two of the same largest numbers, then return it. This paired with Line 2 are already good indications that a some maximum number is returned, but not the most maximum number.

Line 13: If the left side had the larger number, make sure there is no number smaller than that but larger than y (the largest on the right side) At this point saying that the function takes the second largest number makes sense by the recursive use here.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...