CodeBlanks Logo Icon CodeBlanks

Challenge 3

Print the convex hull.

Challenge 3 - Convex hull

The third challenge tests the convex hull algorithm. It computes the hull of a point set using Andrew's monotone chain method.

The count_doublings and kmp_search functions are provided above; you will write convex_hull. Sort points first, then build lower and upper hulls.

This challenge is the third link of the cumulative chain.

Practice convex_hull function

Write convex_hull(points). Return the convex hull of the point list in counterclockwise order. Print [(0, 0), (4, 0), (4, 3), (0, 3)] with print(convex_hull([(0,0), (4,0), (4,3), (0,3), (2,1)])). The count_doublings and kmp_search are provided above.

Starter code

solution.py
def count_doublings(n):
    count = 0
    size = 1
    last = 0
    for i in range(n):
        if last == size:
            size *= 2
            count += 1
        last += 1
    return count

def kmp_search(text, pattern):
    n, m = len(text), len(pattern)
    lps = [0] * m
    length = 0
    i = 1
    while i < m:
        if pattern[i] == pattern[length]:
            length += 1
            lps[i] = length
            i += 1
        elif length != 0:
            length = lps[length - 1]
        else:
            lps[i] = 0
            i += 1
    i = j = 0
    while i < n:
        if text[i] == pattern[j]:
            i += 1
            j += 1
            if j == m:
                return i - j
        elif j != 0:
            j = lps[j - 1]
        else:
            i += 1
    return -1

def convex_hull(points):
    # Return the convex hull

Sample solution

solution.py
def convex_hull(points):
    pts = sorted(set(points))
    if len(pts) <= 1:
        return pts
    def cross(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
    lower = []
    for p in pts:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    upper = []
    for p in reversed(pts):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    return lower[:-1] + upper[:-1]
print(convex_hull([(0,0), (4,0), (4,3), (0,3), (2,1)]))

Expected output

[(0, 0), (4, 0), (4, 3), (0, 3)]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Convex hull concepts

Term Meaning
monotone chain Andrew's method
sorting First step
lower hull Left to right
upper hull Right to left

2 cross product

Question
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[____]) * (b[0] - o[0])
Answer
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

Explanation: a[1] - o[1] is the y component.

3 Which method builds the convex hull?

  • Linear scan
  • DFS
  • Monotone chain Correct answer
  • Greedy

Explanation: The monotone chain (Andrew) method is used.

All lessons in Expert