Skip to contentKEEP THE CRAFTTHE SANCTUARY

Divide and Conquer

Split one input into smaller instances, solve each with the same return contract, then combine their complete results. Count split, merge, copying and stack work rather than assuming every recursive tree is linear.

2 practice exercises5 interview problems

Recognize it when A range can be partitioned into independently solvable smaller ranges.

Checking your account…

Divide and Conquer Code Labs

Split into Independent Subproblems

Divide and conquer works when a problem can be partitioned into smaller independent instances of the same contract. The base case must be complete, and every recursive call must receive a strictly smaller input.

Define the Merge Contract

Before recursing, say what each call returns. The merge step may interleave sorted halves, combine counts, or attach reconstructed subtrees, but it must use only the promised sub-results and preserve every original element.

Trace Recursive Range Splits

Reference
def divide_merge_trace(length):
    ranges = []
    def visit(left, right):
        if left >= right:
            return
        ranges.append([left, right])
        if right - left == 1:
            return
        mid = (left + right) // 2
        visit(left, mid)
        visit(mid, right)
    visit(0, length)
    return ranges
Practice

Implement divide_merge_trace(length). Return all non-empty half-open ranges [left, right] visited by a balanced root-left-right split, stopping at ranges of length one.

Public tests

  • Trace base cases and balanced splits

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Recursive Range Splits

def divide_merge_trace(length):
    ranges = []
    def visit(left, right):
        if left >= right:
            return
        ranges.append([left, right])
        if right - left == 1:
            return
        mid = (left + right) // 2
        visit(left, mid)
        visit(mid, right)
    visit(0, length)
    return ranges

Split Odd-Length Ranges Without Losing an Index

The existing range Lab traces control flow rather than sorting values. Predict root-left-right order for an odd length; equal-sized halves are not required for correctness.

Step Executed statement State Why
Record parent ranges.append([left,right]);mid=(left+right)//2 parent=[0,3], mid=1 Floor division permits unequal child lengths while both are smaller.
Solve left base visit(left,mid);ranges.append([left,right]);if right-left==1:return left child [0,1] recorded once A singleton needs no further split.
Split right child visit(mid,right);ranges.append([left,right]);mid=(left+right)//2 right child=[1,3], its mid=2 The child retains absolute indexes in the original input.
Finish leaves visit(left,mid);visit(mid,right) leaves [1,2] and [2,3] after their visits The three leaves cover indexes 0,1,2 exactly once.
Empty call if left>=right:return ranges=[] An empty range is a complete base case with no recorded node.
Print Output
print(divide_merge_trace(3)) [[0, 3], [0, 1], [1, 3], [1, 2], [2, 3]]
print(divide_merge_trace(0)) []

To transfer to merge sort, add a linear combine operation after each pair of child returns. That extra work changes the linear trace cost to n log n. Tree reconstruction has a different partition rule and may be skewed.

Merge Two Sorted Halves

Reference
def merge_sorted_halves(left, right):
    merged = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            merged.append(left[i])
            i += 1
        else:
            merged.append(right[j])
            j += 1
    merged.extend(left[i:])
    merged.extend(right[j:])
    return merged
Practice

Implement merge_sorted_halves(left, right). Return all values in sorted order without mutating either already-sorted input.

Public tests

  • Merge boundaries and duplicate values

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Merge Two Sorted Halves

def merge_sorted_halves(left, right):
    merged = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            merged.append(left[i])
            i += 1
        else:
            merged.append(right[j])
            j += 1
    merged.extend(left[i:])
    merged.extend(right[j:])
    return merged

Account for Recursion Costs

Write a recurrence. Balanced halves with linear merging give T(n) = 2T(n/2) + O(n) = O(n log n). Python slices copy, so pass indexes when extra copying would add hidden time or space. Recursion also consumes stack frames.

Choose Divide and Conquer or Iteration

Use divide and conquer when subproblems are naturally independent and the combine is clear. Prefer iteration for a simple linear dependency or when Python recursion depth is a risk. Dynamic programming is different: it is valuable when subproblems overlap and should be cached.

Explain It in an Interview

Say: “The base case is complete, the split covers the input without overlap, and each recursive call satisfies the same return contract. The merge reconstructs the full answer.” Then solve the recurrence and count stack and slicing costs. Build Tree from Inorder and Postorder(opens in a new tab) is a representative partition-by-index transfer problem.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Divide and Conquer proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Balanced range traceO(n + 1)O(n + 1)One recorded range per recursion-tree node; no merging of values.
Merge of two sorted listsO(a + b)O(a + b)Every input value is emitted once; leftover slices also copy.
Balanced mergesortO(n log n)O(n log n)Linear combining on each logarithmic level, unlike a range trace.

Space

O(n) range trace or merged output; balanced recursion frames O(log(n+1)); skewed recursive splits can use O(n) frames.

Assumptions

  • The merge Lab requires both inputs already sorted.
  • Slicing in merge tails creates temporary lists; it preserves linear total work but is not O(1) auxiliary space.

Invariants Worth Saying Aloud

  1. Children cover the parent range without omissions or unintended overlap.
  2. Each child result fulfills its complete subrange contract.
  3. Combining results preserves multiplicity, order requirements and every required item.

When To Use Or Avoid Divide and Conquer

Use It When

  • Use balanced range splitting with a known combine contract, such as merging sorted halves.
  • Pass index boundaries when copying every recursive slice would add avoidable allocation.

Choose Another Tool When

  • Use memoization when many calls revisit the same subproblem.
  • Use an iterative recurrence for a simple chain when recursion adds no useful structure.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Including the midpoint in both half-open children

[left,mid) and [mid,right) partition a half-open range. Starting the right child at mid-1 overlaps index mid-1.

Prevent it: Use one shared boundary without duplicating its predecessor.

Avoid

right_child=(mid-1,right)

Use instead

right_child=(mid,right)

Dropping an unconsumed merge tail

If one input empties first, its partner still contains required values. The main loop alone cannot emit them.

Prevent it: Append both remaining tails after the paired comparison loop.

Avoid

merged.extend([])

Use instead

merged.extend(left[i:])
merged.extend(right[j:])

Treating child results as sorted without a premise

Selecting the smaller first head from an unsorted child can emit 4 before an undiscovered 1. The head is minimal only for a sorted child.

Prevent it: Meet the sorted-input merge contract before comparing heads.

Avoid

next_value=min(left[0],right[0])

Use instead

next_value=min(sorted(left)[0],sorted(right)[0])

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.