📓
Everything I Know
  • index
  • #
    • 3D Printing
  • A
    • Abandoned Spaces
    • ADHD
    • Aging
    • Algorithms & Data Structures
      • Array
      • Constraint Satisfaction Problem
      • Dynamic Programming
      • Graph
      • Hash Table
      • Heap
      • Linked List
      • Queue
      • Recursion
      • Set
      • Stack
      • Tree
      • Trie
      • Union Find
    • Amazon Web Services
    • Android
    • Anime, Comics & Manga
    • APIs
    • Artificial Intelligence
    • Assembly
      • ARM
      • MIPS
      • x86
    • Audio / Video Editing
    • Awesome
    • Azure
  • B
    • Board Games
    • Books
  • C
    • C (programming language)
    • C++
    • Cars
    • Cascading Style Sheets
    • Chess
    • Comedy
    • Command Line
      • Autotools
      • Awk
      • Bash scripting
      • Grep
      • Lsof
      • Sed
      • SSH
    • Competitive Programming
    • Compilers
    • Computer Graphics
      • OpenGL
      • Vulkan
      • WebGPU
    • Computer Networks
    • Computer Science
    • Concurrency
    • Continuous Integration / Delivery
    • Cooking
    • Cryptography
    • Cryptocurriencies
    • Curriculum Vitae
  • D
    • Databases
      • PostgreSQL
      • SQL
      • SQLite
    • Design Patterns
    • Digital Minimalism
    • Distributed Systems
    • Docker
    • Documentaries
    • Documentation
    • Domain Name System
    • Dopamine
    • Drawing
  • E
    • eCommerce
    • Electronics
      • Repairs
    • Engineering
    • Entrepreneurship
    • Events
  • F
    • Fashion
    • Fitness
      • Exercise
      • Nutrition
      • Weight Loss
    • Focus
    • Football
  • G
    • Game Development
      • Godot
      • LibGDX
      • Unity
      • Unreal Engine
    • Git
    • Goals
    • Guitar
  • H
    • Habits
    • Happiness
    • House
      • Tradespeople
      • Buying
      • Renting
  • I
    • Interviews
      • Behavioural Interviews
      • Coding Interviews
      • System Design Interviews
  • J
    • Java
    • JavaScript
      • Astro
      • Bun
      • Electron
      • Jest
      • Node.js
      • Nue.js
      • React.js
      • Redux
      • Vue.js
    • Journaling
  • K
    • Karting
    • Knots
    • Knowledge Bases
    • Kotlin
    • Kubernetes
  • L
    • LaTeX
    • Learning
      • Drawing
      • Languages
        • Certificate of Proficiency in English
        • Japanese
      • Piano
    • Legacy Code
    • LEGO
    • Lifestyle
    • Life Hacks
    • Linux
    • LISP
  • M
    • Machine Learning
      • Deep Learning
    • MacOS
    • Maths
    • Meditation
    • Movies
    • Music
      • Music Production
      • Music Theory
  • N
    • Negotiation
    • News
  • O
    • Operating Systems
      • Linux
  • P
    • Parenting
    • Personal Finance
      • ISAs
      • Pensions
    • PHP
    • Physics
    • Podcasts
    • Procrastination
    • Productivity
    • Programming
      • Functional Programming
      • Performance
    • Prometheus
    • Psychology
    • Public Speaking
    • Purpose
    • Puzzles
    • Python
      • Django
      • Pandas
  • Q
    • Quantum Computing
    • Quotes
  • R
    • Regular Expressions
    • Relationships
    • Reverse Engineering
    • Rust
      • Cargo
  • S
    • Security
      • Android
      • Binary Exploitation
      • CompTIA Security+ SYO-701
      • CTFs
      • Forensics
      • Linux
      • Web
      • Windows
    • Self Improvement
    • Shaving
    • Sitting
    • Sleep
    • Social Skills
    • Spring (framework)
    • Stoicism
    • Strength Training
      • Deadlifts
      • Push Ups
    • Success
    • System Design
      • Site Reliability Engineering
  • T
    • Table Tennis
    • Testing
    • Thinking
    • Touch Typing
    • Travel
      • Japan
        • Fukuoka
        • Hiroshima
        • Kyoto
        • Okinawa
        • Osaka
        • Tokyo
      • London
      • Rome
    • TV Series & Programmes
    • Twitch
    • TypeScript
    • Typography
  • V
    • Virtual Tours
    • Vim
    • Video Games
      • Emulation
      • Mods
      • Music
      • Speedrunning
      • Warzone
  • W
    • Web Apps
    • Web Cams
    • Web Development
      • Selenium
      • Web Assembly
    • Windows
      • Windows Development
    • Work
      • Freelancing
      • GitHub Profile
      • Interesting Companies
      • Job Boards
      • Remote Work
      • Startup
    • Writing
Powered by GitBook
On this page
  • Notes
  • How do I recognise a Dynamic Programming problem?
  • Patterns
  • Problems solved using Dynamic Programming
  • Resources
  • Articles
  • Books
  • Courses
  • LeetCode Problems
  • Websites
  • YouTube playlists
  • YouTube videos

Was this helpful?

  1. A
  2. Algorithms & Data Structures

Dynamic Programming

PreviousConstraint Satisfaction ProblemNextGraph

Last updated 1 month ago

Was this helpful?

Notes

  • It's an extension of the Divide and Conquer paradigm

  • It works by recursively breaking down a problem into two or more sub-problems, until these become simple enough to be solved directly. The combination of the solutions for the sub-problems is a solution for the original problem.

  • There are two key attributes that divide and conquer must have in order for dynamic programming to be applicable:

    • - optimal solution can be constructed from optimal solutions of its sub-problems

    • - problem can be broken down into sub-problems which are reused several times, or a recursive algorithm for the problem solves the same sub-problem over and over rather than always generating new sub-problems

  • There are two main techniques of caching and reusing previously computed results:

    • (top-down cache filling): usually done recursively

      memFib(n) {
          if (mem[n] is undefined)
              if (n < 2) result = n
              else result = memFib(n-2) + memFib(n-1)
              mem[n] = result
          return mem[n]
      }
    • Tabulation (bottom-up cache filling): usually done iteratively

      tabFib(n) {
          mem[0] = 0
          mem[1] = 1
          for i = 2...n
              mem[i] = mem[i-2] + mem[i-1]
          return mem[n]
      }

How do I recognise a Dynamic Programming problem?

  1. Recognize a dynamic programming problem. This is often the most difficult step and it has to do with recognizing that there exists a recursive relation. Can your problem result be expressed as a function of results of the smaller problems that look the same?

  2. Determine the number of changing parameters. Express your problem in terms of the function parameters and see how many of those parameters are changing. Typically you will have one or two, but technically this could be any number. Typical examples for one parameter problems are fibonacci or a coin change problem, for two parameter is edit distance.

  3. Clearly express the recursive relation. Once you figure out that the recursive relation exists and you specify the problems in terms of parameters, this should come as a natural step. How do problems relate to each other. That is, assuming that you have computed the subproblems, how would you compute the main problem.

  4. What are your base cases? When you break down sub-problems into smaller sub-problems and you break down those even further, what is the point where you cannot break it anymore? Do all these subproblems end up depending on the same small subproblem or several of them?

  5. Decide if you want to implement it iteratively or recursively and be comfortable with both. Know the trade-offs between one or the other, such as recursive stack overflow, sparsity of computation, think if this is a repeated work or something that you always do online, etc.

  6. Add memoization. If you’re implementing it recursively, add memoization. If you’re doing it iteratively, this will come for free. Adding memoization should be super mechanical. Just see if you have memoized the state at the beginning of your function and add it to memoization before each return statement. Memoization value should almost always be the result of your function.

  7. Time complexity = (# of possible states * work done per each state). This should also be relatively mechanical. Count the number of states that you can have. This will be linear if you have a single parameter, quadratic if you have two and so on. Think about the work done per each state - that is the work that you have to do assuming that you’ve computed all of the subproblems.

Patterns

  1. Minimum (Maximum) Path to React a Target

    • Given a target find minimum (maximum) cost / path / sum to reach the target.

    • Approach: Choose minimum (maximum) path among all possible paths before the current state, then add value for the current state.

    • Generate optimal solutions for all values in the target and return the value for the target (Top-down, Bottom-up).

  2. Distinct Ways

    • Given a target find a number of distinct ways to reach the target.

    • Approach: Sum all possible ways to reach the current state.

    • Generate sum for all values in the target and return the value for the target (Top-down, Bottom-up).

  3. Merging Intervals

    • Given a set of numbers find an optimal solution for a problem considering the current number and the best you can get from the left and right sides.

    • Approach: Find all optimal solutions for every interval and return the best possible answer.

    • Get the best from the left and right sides and add a solution for the current position.

  4. DP on Strings

    • General problem statement for this pattern can vary but most of the time you are given two strings where lengths of those strings are not big

    • Approach: Most of the problems on this pattern requires a solution that can be accepted in O(n^2) complexity.

    • If you are given one string s the approach may little vary

  5. Decision Making

    • The general problem statement for this pattern is forgiven situation decide whether to use or not to use the current state. So, the problem requires you to make a decision at a current state.

    • Approach: If you decide to choose the current value use the previous result where the value was ignored; vice-versa, if you decide to ignore the current value use previous result where value was used.

Problems solved using Dynamic Programming

Resources

Articles

Books

Courses

LeetCode Problems

Websites

YouTube playlists

YouTube videos

Problem List:

Problem List:

Problem List:

Problem List:

Problem List:

- given a set of n integers between 0 and K, partition these integers into two sets so that |sum(S1) - sum(s2)| is minimal

- given a staircase with n steps to the top, and you can climb x or y steps, in how many disinct ways can you reach the top of the staircase?

- given an infinite supply of coins with different values and a target price, in how many distinct ways can we make the change?

- what is the n-th number in the Fibonacci sequence?

- given a set of items, each with a weight and a value, what is the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible?

- given two strings, what is the longest subsequence (=non necessarily contiguous) for which letters from the two strings appear in the same order?

- given an array of integers, which contiguous subarray has the largest sum?

Minimum Edit Distance (or ) - what is the minimum number of single-character edits (insertions, deletions, or subsitutions) required to change one word into another?

- LeetCode

- Quentin Santos

- Oleksii Trekhleb

- programming.guide

- Nikola Otasevic

- Jesse Farmer

- Quora

Introduction To Algorithms, Chapter 15: Dynamic Programming (, )

- MIT

- Udemy

- Educative

- Udemy

- Udemy

- Michael A. Trick

- Brian Dean

- Tushar Roy

- William Fiset

- NPTEL

- Stanford CS221

- Coding Patterns

Optimal substructure
Overlapping sub-problems
Memoization
DP (Max - Min)
DP (distinct ways)
DP (merging intervals)
DP on strings
DP (decision making)
Balanced Partition
Climbing Stairs
Coin Change
Fibonacci Sequence
House Robber
Knapsack
Longest Common Subsequence
Maximum Subarray Sum
Levenshtein Distance
DP IS EASY! 5 Steps to Think Through DP Questions
Dynamic Programming is not Black Magic
Dynamic Programming vs Divide-and-Conquer
Dynamic programming vs memoization vs tabulation
Dynamic Programming – 7 Steps to Solve any DP Interview Problem
Introduction to Dynamic Programming
What are the top 10 most popular dynamic programming problems among interviewers?
Algorithms, Chapter 6: Dynamic Programming
lecture
notes
Dynamic Programming
Dynamic Programming - I
Grokking Dynamic Programming Patterns for Coding Interviews
Intro To Dynamic Programming - Coding Interview Preparation
Master the art of Dynamic Programming
Best Time to Buy and Sell Stock
Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock IV
Best Time to Buy and Sell Stock with Cooldown
Best Time to Buy and Sell Stock with Transaction Fee
Burst Balloons
Climbing Stairs
Combination Sum IV
Distinct Subsequences
Domino and Tromino Tiling
Edit Distance
Guess Number Higher or Lower II
House Robber
Knight Probability in Chessboard
Longest Common Subsequence
Longest Palindromic Subsequence
Longest Palindromic Substring
Minimum ASCII Delete Sum for Two Strings
Minimum Cost to Merge Stones
Minimum Cost Tree From Leaf Values
Minimum Score Triangulation of Polygon
Number of Longest Increasing Subsequence
Out of Boundary Paths
Palindromic Substrings
Partition Equal Subset Sum
Remove Boxes
Shortest Common Supersequence
Target Sum
Unique Binary Search Trees
Unique Paths
Unique Paths II
A Tutorial on Dynamic Programming
Dynamic Programming Practice Problems
Dynamic Programming
Dynamic Programming
Dynamic Programming
Dynamic Programming and Uniform Cost Search
Dynamic Programming for people who hate it