Skip to content
CodeItRaw
Recursion & Divide and Conquer

Lesson 2/3

Smaller does not always mean "one less". You can shrink a list by peeling one element off each end, or by cutting it in the middle and throwing half away. The way you choose decides how many calls are made.

def find(values, key, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if values[mid] == key:
return mid
if values[mid] < key:
return find(values, key, mid + 1, hi)
return find(values, key, lo, mid - 1)
Searching a sorted list: look at the middle, and if what you want is larger, drop the whole left half. The list is not copied; only the bounds lo and hi close in. Each call halves what is left, so a thousand elements take ten calls.

Peeling from both ends is the same pattern: if the ends agree, call yourself for what is left inside; if they do not, the answer is known at once. The base case is one element left, or none.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Mirror

    Function

  2. 02

    Binary Search

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list