CodeBlanks Logo Icon CodeBlanks

Summary - Divide and conquer

Solve a problem by dividing it in a mini task.

Summary - Divide and conquer

Divide and conquer solves problems by dividing, conquering recursively and combining. Merge sort, quick sort and binary search use it.

In this mini task you will count using divide and conquer; combine all steps.

The approach also runs well on parallel hardware; subproblems are independent.

Practice Divide and count

Write dc_count(arr, target). Split in half, count target recursively in each half, add. Print 3 with print(dc_count([1, 2, 1, 3, 1], 1)).

Starter code

solution.py
def dc_count(arr, target):
    # Divide and count

Sample solution

solution.py
def dc_count(arr, target):
    # Divide and count
    if len(arr) == 0:
        return 0
    if len(arr) == 1:
        return 1 if arr[0] == target else 0
    mid = len(arr) // 2
    return dc_count(arr[:mid], target) + dc_count(arr[mid:], target)
print(dc_count([1, 2, 1, 3, 1], 1))

Expected output

3

Questions and answers

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

1 Summary - Divide and conquer: match the terms

Term Meaning
divide Split
conquer Solve
combine Merge
base case Stop

2 Find mid

Question
mid = len(arr) ____ 2
Answer
mid = len(arr) // 2

Explanation: // is right.

3 Where is divide and conquer used?

  • Linear search
  • Merge sort, quick sort Correct answer
  • Bubble sort
  • Heap only

Explanation: Merge sort, quick sort.

All lessons in Intermediate