Posts

Recursion vs Dynamic Programming

  Recursion vs Dynamic Programming Aspect Recursion Dynamic Programming (DP) Basic Idea Solves a problem by breaking it down into smaller sub-problems, often leading to repeated calculations of the same sub-problems. Solves a problem by breaking it down into smaller sub-problems, but stores the results of these sub-problems to avoid redundant calculations. Overlapping Sub-Problems Sub-problems are often recalculated multiple times because results are not stored. Sub-problems are solved once and their results are stored (usually in a table) for reuse. Optimal Substructure Can be used if the problem exhibits optimal substructure, but does not explicitly take advantage of it unless combined with memoization. Explicitly takes advantage of optimal substructure by building up the solution from the smallest sub-problems. Time Complexity Can be exponential in many cases (e.g., O(2^n) for Fibonacci) due to repeated calculations. Often reduces time complexity to polynomial (e.g., O(n) for Fi...

Dynamic Programming

Dynamic Programming  Dynamic Programming (DP) is an important problem-solving strategy in algorithmic thinking. It is mainly used when a problem can be divided into smaller sub-problems , and the same sub-problems occur repeatedly. The central idea is: Solve each sub-problem only once, store its result, and reuse it whenever needed. A simple way  to remember DP is: DP = Divide the problem + Solve the subproblem + Remember the answers 1. Why Do We Need Dynamic Programming? Consider the Fibonacci sequence: 0 ,   1 ,   1 ,   2 ,   3 ,   5 ,   8 ,   13 , … The Fibonacci numbers are defined as: 𝐹 ( 𝑛 ) = 𝐹 ( 𝑛 − 1 ) + 𝐹 ( 𝑛 − 2 ) For example: 𝐹 ( 5 ) = 𝐹 ( 4 ) + 𝐹 ( 3 ) A straightforward recursive solution repeatedly calculates the same values. F(5) / \ F(4) F(3) / \ / \ F(3) F(2) F(2) F(1) / \ F(2) F(1) Notice that...

Divide and Conquer

Image
Divide and Conquer Strategy Divide and Conquer is a problem-solving strategy in which a large and complex problem is divided into smaller problems , each smaller problem is solved separately, and then the solutions are combined to obtain the solution to the original problem. Simple idea “Break a big problem into smaller problems, solve them, and combine the answers.” This strategy is especially important in algorithm design because many difficult problems become easier when we work with smaller pieces. The Three Steps Divide and Conquer generally has three stages : 1. Divide Break the original problem into smaller sub-problems . The smaller problems should be easier to handle and usually have the same nature as the original problem . Example: Suppose we have 1,000 books to organize. Instead of organizing all 1,000 books together: 1000 Books ↓ ┌───┼────┐ ↓ ↓ ↓ Fiction Non-fiction Reference We have divided one large problem into smaller problems. 2. Conquer Solve each...