</>
Skip to content
DSA lessons (49/55)

DSA — Divide and Conquer

What is Divide and Conquer?

  1. Divide the problem into subproblems
  2. Conquer each subproblem recursively
  3. Combine the results

Merge Sort (Classic Example)

def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    
    return merge(left, right)

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

Quick Sort

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    
    return quick_sort(left) + middle + quick_sort(right)

Binary Search

def binary_search(arr, target, left=0, right=None):
    if right is None:
        right = len(arr) - 1
    
    if left > right:
        return -1
    
    mid = (left + right) // 2
    
    if arr[mid] == target:
        return mid
    elif arr[mid] < target:
        return binary_search(arr, target, mid + 1, right)
    else:
        return binary_search(arr, target, left, mid - 1)

Time Complexity

AlgorithmComplexity
Merge SortO(n log n)
Quick SortO(n log n) avg
Binary SearchO(log n)

Mini Practice

  1. Implement merge sort
  2. Implement quick sort
  3. Solve maximum subarray
  4. Find closest pair of points

Up Next

Continue with Sliding Window — sliding window technique.

Related Topics

Frequently Asked Questions about Divide and Conquer

What is Divide and Conquer in DSA?

Divide and Conquer is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Divide and Conquer?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Divide and Conquer.

Why is Divide and Conquer important in DSA?

Divide and Conquer is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.