Divide and Conquer Strategy and Recurrence Relations in DSA Javascript - Time & Space Complexity
Divide and conquer breaks a problem into smaller parts, solves each part, then combines results.
We want to know how the total work grows as the problem size grows.
Analyze the time complexity of this recursive divide and conquer code.
function divideAndConquer(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = divideAndConquer(arr.slice(0, mid));
const right = divideAndConquer(arr.slice(mid));
return merge(left, right);
}
function merge(left, right) {
// Merges two sorted arrays into one sorted array
let result = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
result.push(left[i++]);
} else {
result.push(right[j++]);
}
}
return result.concat(left.slice(i)).concat(right.slice(j));
}
This code splits an array into halves, sorts each half recursively, then merges them.
Look at the recursive calls and merging steps.
- Primary operation: Splitting array and merging sorted halves.
- How many times: The array is split into halves repeatedly until size 1, then merged back.
Each split halves the problem, but merging takes time proportional to the current size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 * log2(10) ≈ 33 merges |
| 100 | About 100 * log2(100) ≈ 664 merges |
| 1000 | About 1000 * log2(1000) ≈ 9966 merges |
Pattern observation: Operations grow a bit faster than linear, roughly linear times log of input size.
Time Complexity: O(n log n)
This means the work grows a little more than linearly as input size grows, due to repeated splitting and merging.
[X] Wrong: "Because the array is split in half each time, the time is just O(log n)."
[OK] Correct: Splitting reduces problem size, but merging takes linear time each level, so total work is more than just log n.
Understanding divide and conquer and its time helps you explain many algorithms clearly and confidently.
"What if the merge step took constant time instead of linear? How would the time complexity change?"
Practice
Divide and Conquer strategy in algorithms?Solution
Step 1: Understand the divide and conquer approach
It splits a big problem into smaller parts that are easier to solve.Step 2: Combine the solutions of smaller parts
After solving subproblems, their results are merged to get the final answer.Final Answer:
Break the problem into smaller subproblems, solve them independently, then combine results -> Option CQuick Check:
Divide and conquer = split, solve, combine [OK]
- Confusing divide and conquer with brute force
- Thinking it uses only one loop
- Mixing it with dynamic programming
Solution
Step 1: Recall Merge Sort recurrence
Merge Sort splits array into two halves, sorts each half, then merges in O(n).Step 2: Write recurrence form
It calls itself twice on half size (2T(n/2)) plus linear merge time O(n).Final Answer:
T(n) = 2T(n/2) + O(n) -> Option BQuick Check:
Merge Sort recurrence = 2T(n/2) + n [OK]
- Using T(n-1) instead of T(n/2)
- Adding O(n^2) instead of O(n)
- Confusing with Quick Sort recurrence
function sumArray(arr) {
if (arr.length === 1) return arr[0];
const mid = Math.floor(arr.length / 2);
return sumArray(arr.slice(0, mid)) + sumArray(arr.slice(mid));
}
console.log(sumArray([2, 4, 6, 8]));Solution
Step 1: Understand the function behavior
The function splits the array into halves recursively and sums elements.Step 2: Trace the calls for [2,4,6,8]
Split into [2,4] and [6,8], sumArray([2,4]) = 6, sumArray([6,8]) = 14, total 20.Final Answer:
20 -> Option AQuick Check:
Sum of 2+4+6+8 = 20 [OK]
- Confusing slice indices causing wrong sums
- Assuming function returns array instead of sum
- Forgetting base case for single element
function findMax(arr) {
if (arr.length === 1) return arr[0];
const mid = Math.floor(arr.length / 2);
const leftMax = findMax(arr.slice(0, mid));
const rightMax = findMax(arr.slice(mid));
return leftMax > rightMax ? leftMax : rightMax;
}
console.log(findMax([]));Solution
Step 1: Check base case for empty array
The function does not handle empty array input, so arr.length === 0 is not checked.Step 2: Understand recursion on empty array
Calling findMax([]) leads to infinite recursion because base case is only for length 1.Final Answer:
Fails on empty array input causing infinite recursion -> Option AQuick Check:
Empty input needs base case to avoid infinite calls [OK]
- Ignoring empty array edge case
- Assuming slice always returns non-empty array
- Thinking comparison operator is wrong
T(n) = 3T(n/3) + n, what is the time complexity using the Master Theorem?Solution
Step 1: Identify parameters for Master Theorem
Here, a=3, b=3, f(n)=n. Calculate log_b(a) = log_3(3) = 1.Step 2: Compare f(n) with n^log_b(a)
f(n) = n and n^log_b(a) = n^1 = n, so f(n) = Theta(n^log_b(a)).Step 3: Apply Master Theorem case 2
When f(n) = Theta(n^log_b(a)), T(n) = Theta(n log n).Final Answer:
O(n log n) -> Option DQuick Check:
Master Theorem case 2 = n log n [OK]
- Confusing log base or parameters a and b
- Choosing wrong Master Theorem case
- Ignoring the extra n term in recurrence
Ready to prove it?
Pass the test and this pattern moves unknown
