Divide and Conquer
Divide and Conquer
Divide and Conquer
Introduction
• Overview: Divide and Conquer is an algorithmic paradigm that breaks a problem into smaller
subproblems, solves each subproblem, and combines the results to solve the original problem.
• Importance in coding interviews: It is used for optimizing solutions where brute force is impractical
due to high time complexity.
Key Concepts
• Divide: Continue splitting the complex problem into smaller and manageable parts until the solution
is trivial.
• Conquer: Solve each subproblem, typically simpler than the original problem.
• Combine: Merge the results of the subproblems to form a solution to the original problem.
Problem
Divide
Subproblem 1 Subproblem 2
Solve Solve
Conquer
Subproblem Subproblem
Solution to Solution to
Subproblem 1 Subproblem 2
Combine
Solution to
Subproblem
Search 20
15 20 25 30 35 40
15 20 25 30 35 40
15 20 25 30 35 40
Divide and Conquer Techniques for Coding Interviews
2 Algorithm: Merge Sort
Explanation: Divides the array into halves, sorts each half, and merges them.
Time Complexity: O(n log n)
38 27 43 10
38 27 43 10
38 27 43 10
27 38 10 43
10 27 38 43
38 27 43 10 Pivot
<=10 10<
10 38 27 43 Pivot
<=43 43<
10 38 27 Pivot 43
<=27 27<
10 27 38 43
10 27 38 43
PL PR
Divide and Conquer Techniques for Coding Interviews
5 Algorithm: Fast Exponentiation
Explanation: Calculates large powers efficiently by repeatedly squaring the base.
Time Complexity: O(log n)
25
21 22 22
21 21 21 21
20 20 20 20 20
1 2 3 4 17 18 19 20
5 6 7 8 21 22 23 24
A= B=
9 10 11 12 25 26 27 28
13 14 15 16 29 30 31 32
1 2 3 4 9 10 11 12
A11 = , A12 = , A21 = A
, 22 =
5 6 7 8 13 14 15 16
A11 A12 B B
A= , B = 11 12
A21 A22 B21 B22
17 18 19 20 25 26 27 28
B11 = , B12 = , B21 = , B22 =
21 22 23 24 29 30 31 32