Divide and Conquer is the recursive halving strategy. Instead of solving a problem of size n directly, split it into smaller subproblems (usually halves), solve each recursively, and combine the results. The power comes from reducing O(n²) to O(n log n).
Problem: Count pairs (i, j) where i < j but arr[i] > arr[j].Insight: Modified merge sort. During merge, when we pick from right half, all remaining left elements form inversions.
Copy
long long mergeCount(vector<int>& arr, int lo, int mid, int hi) { vector<int> temp(hi - lo + 1); int i = lo, j = mid + 1, k = 0; long long inversions = 0; while (i <= mid && j <= hi) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inversions += (mid - i + 1); // All remaining left elements } } while (i <= mid) temp[k++] = arr[i++]; while (j <= hi) temp[k++] = arr[j++]; for (int i = lo; i <= hi; i++) arr[i] = temp[i - lo]; return inversions;}long long countInversions(vector<int>& arr, int lo, int hi) { if (lo >= hi) return 0; int mid = lo + (hi - lo) / 2; long long count = 0; count += countInversions(arr, lo, mid); count += countInversions(arr, mid + 1, hi); count += mergeCount(arr, lo, mid, hi); return count;}
Problem: Find contiguous subarray with maximum sum.D&C Approach: Max subarray is either entirely in left, entirely in right, or crosses the middle.
Copy
struct Result { long long maxSum; // Maximum subarray sum long long prefixSum; // Maximum prefix sum long long suffixSum; // Maximum suffix sum long long totalSum; // Total sum of segment};Result solve(vector<int>& arr, int lo, int hi) { if (lo == hi) { return {arr[lo], arr[lo], arr[lo], arr[lo]}; } int mid = lo + (hi - lo) / 2; Result left = solve(arr, lo, mid); Result right = solve(arr, mid + 1, hi); Result combined; combined.totalSum = left.totalSum + right.totalSum; combined.prefixSum = max(left.prefixSum, left.totalSum + right.prefixSum); combined.suffixSum = max(right.suffixSum, right.totalSum + left.suffixSum); combined.maxSum = max({left.maxSum, right.maxSum, left.suffixSum + right.prefixSum}); return combined;}
// WRONG: Infinite recursion when lo == hiif (lo > hi) return;// CORRECTif (lo >= hi) return;
Mistake 2: Stack Overflow
D&C depth is O(log n) for balanced splits, but O(n) for unbalanced (like quicksort worst case). Use iterative or randomized pivot.
Mistake 3: Inefficient Combine
If combine is O(n²), you lose the benefit:
Good: O(n) combine → O(n log n) total
Bad: O(n²) combine → O(n² log n) total (worse than brute force!)