Skip to content
DSA in JavaScript
← All patterns

Divide & Conquer

0/12 solved

What it is

Split the problem into independent halves, solve each, then combine the answers.

Used for

Merge sort, quicksort, counting inversions, building a tree from traversals.
array
6
3
8
2

Step 1 of 6

Goal: sort [6, 3, 8, 2]. Big problems are hard and tiny ones are easy. Split in half until every piece is a single number (already sorted), then join the pieces back together in order.

You see

  • Problem splits into independent halves
  • Combine step is cheap
  • Recurrence like T(n) = 2T(n/2) + n

Learn it in

RecursionMerge SortQuicksortFast Powering AlgorithmTower of HanoiBinary Search

Template

function mergeSort(a) {  if (a.length < 2) return a;  const mid = a.length >> 1, l = mergeSort(a.slice(0, mid)), r = mergeSort(a.slice(mid));  const out = [];  while (l.length && r.length) out.push(l[0] <= r[0] ? l.shift() : r.shift());  return [...out, ...l, ...r];}

Practice problems