<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Raghav Gupta on Medium]]></title>
        <description><![CDATA[Stories by Raghav Gupta on Medium]]></description>
        <link>https://medium.com/@connectto.guptaraghav?source=rss-b16f542a4a86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7iSKr4qUbVUXrOtTtSNvAQ.jpeg</url>
            <title>Stories by Raghav Gupta on Medium</title>
            <link>https://medium.com/@connectto.guptaraghav?source=rss-b16f542a4a86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:27:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@connectto.guptaraghav/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Dynamic Programming: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@connectto.guptaraghav/mastering-dynamic-programming-a-step-by-step-guide-741d9d7d142?source=rss-b16f542a4a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/741d9d7d142</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Raghav Gupta]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 18:23:27 GMT</pubDate>
            <atom:updated>2023-09-07T18:58:39.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KF5nloJhPaPfb_81MzhWZg.png" /><figcaption>Dynamic Programming</figcaption></figure><p>Dynamic programming can be an intimidating topic, but with the right approach, it becomes a powerful problem-solving tool. In this guide, I’ll break down the process into easy-to-follow and easy-to-understand steps that will help you navigate and conquer dynamic programming problems.</p><h3>Step 0: Identifying Dynamic Programming Problems.</h3><p>To recognize whether a problem can be effectively solved using dynamic programming, pay attention to certain clues within the problem description. Look for keywords such as “maximum” or “minimum,” as well as indications that the solution needs to be optimized for efficiency.</p><p>Additionally, consider whether the problem can be broken down into smaller sub-problems that can be solved independently. If you notice that these sub-problems share common calculations, it’s a sign that dynamic programming might be applicable. This approach helps avoid redundant computations and leads to optimized solutions. Generally, a common practice to solve such questions is by using recursion and backtracking.</p><p>If you can narrow down these indicators from the problem statement, you can quickly assess whether a given problem can be solved using dynamic programming or not.</p><h3>Step 1: understanding what path you should be following to solve the problem.</h3><p>Let’s make things a little clear that I said above : If you have understood the basics of Dynamic programming well enough then start drawing patterns out these basic questions; if not then go and solve the questions or read thoroughly about these questions to make the most of these questions I will recommend keep asking why a solution did a certain thing.</p><p>Questions:</p><ul><li>0/1 Knapsack and unbounded knapsack</li><li>shortest Path</li><li>finding sub sequences and/or Longest common sub string</li><li>Fence painting algorithm</li><li>rod-cutting problem</li><li>Matrix chain multiplication</li></ul><p>Most of the problems will be a variation of some of the questions above. NOT SAME but might follow a similar approach that can help you understand what’s going on.</p><h3>Step 1 a. writing a brute force solution:</h3><p>Once you have recognized what path to follow let’s focus on writing a brute force solution. The brute force solution should generally be a recursive solution. And let’s be honest most of us here are preparing for an interview and it’s best to cook the solution from the brute force solution to the best or the most optimized.</p><p>I am hoping you are already good at writing a recursive solution if not I will cover that in a different blog soon.</p><p>But to help you understand the approach better I will still write a code structure below:</p><p>I am using a cut rod segments example here:</p><pre>int solve(int n, int x, int y, int z) {</pre><pre>  if (n == 0) { //base condition<br>	  return 0; <br>  }<br>  if (n &lt; 0) { //base condition<br>	  return INT_MIN; <br>  }</pre><pre>  int a = solve(n-x, x,y,z)+1; //considering x length cut<br>  int b = solve(n-y,x,y,z)+1; //considering y length cut<br>  int c = solve(n-z,x,y,z)+1;//considering z length cut</pre><pre>  int ans = max(a, max(b,c)); //finding the maximum out of the three. <br>  return ans; //returning the answer.</pre><pre>}</pre><h3>Step 2: recognizing which state updates in your recursive solution.</h3><p>→ This is a crucial step to understand what kind of Dp data structure or if this Dynamic problem will be a 1-D dp or a 2-D dp.</p><p>Understanding which state is updated in your recursive solution is pivotal. It helps you decide whether to use a 1-D or 2-D dynamic programming approach. In the snippet above, we only update “n,” indicating a 1-dimensional data structure.</p><pre>vector&lt;int&gt; dp(n+1, -1);</pre><p>BUT for anybody who doesn’t like to code in c++, we have a created a dynamic array of n+1 size and pre-filled all the elements as -1.</p><p>WHY <strong>n+1?</strong></p><p>→ +1 : because our indexing starts from 0 and not 1.</p><p>→ n : because that’s the state we are most concerned about and tracking that.</p><p>→ -1 : By setting the initial value of each element in the DP array to -1, we indicate that these values haven’t been calculated yet. Since negative lengths are not relevant to our problem context, this value won’t be updated during the solution, allowing us to easily distinguish between calculated and uncalculated states.</p><p>This helps us understand WHY are we doing specific things.</p><h3>Step 3: converting the recursive solution to a memoization solution.</h3><p>→ Dynamic programming solutions enable you to systematically keep track of the decisions you’ve made and those pending. The initial value of “-1” signifies that no decisions have been made yet. As the solution progresses, these values are updated to indicate that decisions have been made and the corresponding outcomes have been recorded.</p><p>→ NOTE: I am going to recommend to follow a method that requires you to just blind foldedly follow what I am telling you but you should be more aware as you practice more.</p><ol><li>pass the dp array to your recursive function call. :</li><li>The base conditions remains the same but we need to add one more base condition: if you guessed checking the dp[index] solution then you are correct.</li></ol><pre>if (n == 0) { //base condition<br>	  return 0; <br>  }<br>  if (n &lt; 0) { //base condition<br>	  return INT_MIN; <br>  }<br>	if(dp[n]!=-1){ //check if it&#39;s already been updated.<br>	  return dp[n];<br>  }</pre><ol><li>Remember that you need to update the dp[index] value so you need to return that value instead of “ans” .</li></ol><pre>int a = solve(n-x, x,y,z)+1; //considering x length cut<br>  int b = solve(n-y,x,y,z)+1; //considering y length cut<br>  int c = solve(n-z,x,y,z)+1;//considering z lenghth cut</pre><pre>  int ans = max(a, max(b,c)); //finding the maximum out of the three. <br>  return ans; //returning the answer.</pre><pre>int a = solveMem(n-x, x,y,z,dp)+1;<br>  int b = solveMem(n-y,x,y,z,dp)+1;<br>  int c = solveMem(n-z,x,y,z,dp)+1;</pre><pre>  dp[n] = max(a, max(b,c));<br>  return dp[n];</pre><p>keeping these side by side will make a lot more sense.</p><ol><li>and Voila you have a memoized Dp solution.</li></ol><h3>Step 4 : converting the memoized solution to a tabular method(bottom-up).</h3><p>→ Tabular method will also need a dp Array to solve the problem but the way we approach is different.</p><p>We don’t pass the dp array as one of the arguments in the function call.</p><p>We instead create the dp array in this function itself, It’s important to note that this approach follows a bottom-up strategy, where the priority is given to achieving the final outcome by initially focusing on the last step of the process.</p><pre>int solveTab(int n, int x, int y, int z) {<br>  <br>  vector&lt;int&gt; dp(n+1,INT_MIN);<br> }</pre><p>→ Look at the base conditions and try to store the values in the dp array.</p><p>what do I mean by that:</p><pre>if (n == 0) { //base condition<br>	  return 0; <br>  }</pre><pre>dp[0]= 0;</pre><p>→ We knew that when we reach the 0th index we need to store 0.</p><p>→ But what about the other base condition ? well we tackled it in the pre-filled value.</p><p>→ The next thing that we will be doing is to convert the recursive solution to iterative solution. And so it is obvious that we will be using for loops instead.</p><pre>for (int i = 1; i &lt;=n; i++) { //this is mimicking the recursive solution iterations from 1 to n<br>	if(i-x&gt;=0) //in case we run out of bounds we put a check<br>		dp[i] = max(dp[i],dp[i-x]+1); <br>        if(i-y&gt;=0)<br>		dp[i] = max(dp[i],dp[i-y]+1); <br>        if(i-z&gt;=0)<br>		dp[i] = max(dp[i],dp[i-z]+1); <br>	  <br>  }</pre><p>→ The final step is to return the appropriate answer.</p><pre>if(dp[n]&lt;0){ //it means it was never achieved, as you remember from the initation <br>	  return 0; <br>}<br>else<br>	  return dp[n]; <br>}</pre><p>And you have wrote the tabulized solution successfully. Now you need to follow this same method for every solution to write the solutions.</p><p>If you see we have solved an exponential brute force solution and then optimized to work in linear time complexity solution.</p><h3>Step 5: space optimization.</h3><p>→ if you notice we are still consuming O(n) space to solve this problem which is not the best thing always. So we need to see if we can solve it O(1) space.</p><p>→ Unfortunately we won’t be able to come up with a O(1) space solution, at least I couldn’t but i will still tell you the process.</p><p>→ look carefully at the calls:</p><pre>dp[i] = max(dp[i],dp[i-x]+1);</pre><p>we can optimize these if we knew what the dp[i-x] value going to be. let’s say its the previous value.</p><p>In other words dp[i] was dependent on dp[i-1] and/or dp[i-2] ; In this situation we knew that just keeping a track of two previous value will help us solve it so we can get rid of the dp array instead.</p><p>Although achieving O(1) space is usually not feasible, understanding the concept is essential. Analyze the dependencies in your solution and consider whether you can optimize memory usage by tracking fewer values.</p><p>By following these steps, you’ll transform a naive brute force solution into an optimized dynamic programming solution, enabling you to tackle complex problems efficiently.</p><p>Remember, practice is key. Work through various dynamic programming problems to gain confidence and familiarity with different scenarios.</p><p>Happy problem-solving!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=741d9d7d142" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>