LEARN A CODING
INTERVIEW PATTERN:
DYNAMIC PROGRAMMING
HOW DOES DYNAMIC PROGRAMMING WORK?
Many problems are solved using a
divide-and-conquer approach recursively.
In these problems, we see an optimal substructure,
i.e., the solution to a smaller problem helps us solve
the bigger one.
In some of the problems that can be solved with
the above approach, there are many overlapping
sub-problems. That is, we find ourselves solving the
same sub-problem over and over.
Let’s look at an example on the next slide.
HOW DOES DYNAMIC PROGRAMMING WORK?
An example is the recursive fib (4)
computation of the nth fib (3) fib (2)
Fibonacci number. Here’s
fib (1) fib (2) fib (1) fib (0)
the recursion tree for the
solution to this problem fib (0) fib (1)
with n = 4.
We can see above that fib(2) is evaluated twice, fib(1) is
evaluated thrice, and fib(0) is evaluated twice. These are
repeated overlapping subproblems.
The dynamic programming pattern is used to store this
result and utilize it whenever the subproblem is repeated.
THE TWO MAIN APPROACHES OFDYNAMIC PROGRAMMING:
Top-down approach: A recursive approach that stores
the results of redundant function calls to avoid
repeating calculations for the same subproblems.
Bottom-up approach: An iterative strategy that
systematically fills a table with subproblem results to
solve larger problems efficiently.
USE DYNAMIC PROGRAMMING:
If your coding problem has
overlapping subproblems.
If your coding problem has
optimal substructure.
DON'T USE DYNAMIC PROGRAMMING:
If your problem has non-
overlapping subproblems.
If your problem violates the
optimal substructure property.
REAL-WORLD APPLICATIONS OF DYNAMIC PROGRAMMING:
Optimal route planning in GPS navigation systems:
Iteratively explores all possible paths to determine the
optimal route that minimizes travel time.
Robotics motion planning: Explores different paths
and evaluates the associated costs, determining the
optimal trajectory.
KEEP GOING!
Test out your new knowledge of
Dynamic Programming by solving
the popular 0/1 Knapsack problem!
Happy learning!