<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: vickdayaram</title>
    <description>The latest articles on DEV Community by vickdayaram (@vickdayaram).</description>
    <link>https://dev.to/vickdayaram</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F806339%2F6bb3a62a-80dc-489f-b03c-8a140d1421af.jpeg</url>
      <title>DEV Community: vickdayaram</title>
      <link>https://dev.to/vickdayaram</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/vickdayaram"/>
    <language>en</language>
    <item>
      <title>LeetCode 10. Regular Expression Matching, Dynamic Programming Edition</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sun, 01 May 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-10-regular-expression-matching-dynamic-programming-edition-1c1o</link>
      <guid>https://dev.to/vickdayaram/leetcode-10-regular-expression-matching-dynamic-programming-edition-1c1o</guid>
      <description>&lt;p&gt;Solving LeetCode 10, Regular Expression Matching with Dynamic Programming. &lt;a href="https://leetcode.com/problems/regular-expression-matching/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;p&gt;To get the most out of this post I recommend you read my &lt;a href="https://dev.to/vickdayaram/leetcode-10-regular-expression-matching-3eem"&gt;original post&lt;/a&gt; that covers the analysis and the recursive solution. We will use that analysis and focus on how we can implement a solution using Dynamic Programming.&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;Given an input string s and a pattern p, implement regular expression matching with support for ’.’ and ’*’ where:&lt;/p&gt;

&lt;p&gt;’.’ Matches any single character.​​​​ ’*’ Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Breaking it down
&lt;/h3&gt;

&lt;p&gt;Lets understand how we can apply Dynamic Programming to solve this problem. If you are not familiar with Dynamic Programming at all, I’d recommend that you learn the basics first before diving into this post.&lt;/p&gt;

&lt;h4&gt;
  
  
  Analysis Recap
&lt;/h4&gt;

&lt;p&gt;When we have an exact match, move on to the next character. An exact match can happen in two ways:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Characters match exactly&lt;/li&gt;
&lt;li&gt;Pattern contains a ”.”&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If the next character ahead is a ”*” we have to asses the remainder of the string in one of two ways:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Match zero characters of the preceding character in the pattern&lt;/li&gt;
&lt;li&gt;Match one or more characters of the preceding character in the pattern&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Applying Dynamic Programming
&lt;/h4&gt;

&lt;p&gt;Dynamic Programming is described as solving a problem bottom up. The core strategy is as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Identify your base cases (Solutions for small sub problems that you already know)&lt;/li&gt;
&lt;li&gt;Build solutions for small sub problems from base cases&lt;/li&gt;
&lt;li&gt;Use the previous solutions to build solutions for more complex cases, and so on&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This will become more clear as we get into the implementation of the algorithm.&lt;/p&gt;

&lt;p&gt;To keep track of all of these sub problems we will use a matrix. We’ll refer to this as our DP table. Using a matrix is fairly common in Dynamic Programming although other data structures could be used as well.&lt;/p&gt;

&lt;h4&gt;
  
  
  Example one
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/46d5e9de98cb224a4f5402474b1f53df/a9b70/Input.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9aSk37xp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/46d5e9de98cb224a4f5402474b1f53df/a9b70/Input.png" alt="Input" title="Input" width="479" height="155"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h5&gt;
  
  
  Structuring our DP Table
&lt;/h5&gt;

&lt;p&gt;To structure our table we need to answer the following:&lt;/p&gt;

&lt;p&gt;What are our base cases? They will be the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Empty Pattern, Empty String&lt;/li&gt;
&lt;li&gt;Empty Pattern&lt;/li&gt;
&lt;li&gt;Empty String&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What kind of values will our table store? We can build a table of boolean values. If the sub string and sub pattern match, we can tag it with True, otherwise False&lt;/p&gt;

&lt;p&gt;As we iterate through we will be referencing our table for solutions to previous sub problems. We will use those solutions to solve our current problems, and use solutions to current problems to solve the next problems, and so on. Working in a bottom up fashion!&lt;/p&gt;

&lt;p&gt;With that in mind, this is what our table would look like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/10800f427f480b259ab49b1162a2a4a6/b5245/DpTable.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8HmeoxvA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/10800f427f480b259ab49b1162a2a4a6/b5245/DpTable.png" alt="DpTable" title="DpTable" width="535" height="350"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Important Note: I chose to place the pattern on the X axis and the string in the Y axis. You can orient the table however you want, but be mindful of how you orient your inputs since it will affect how you search your table.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h5&gt;
  
  
  Populating our base cases
&lt;/h5&gt;

&lt;p&gt;Before iterating through and solving for sub problems we need to initialize our table with the solutions to our base cases. These cases represent the small sub problems that we already know the answer to. Just like in a recursive algorithm, dynamic programming will build our solution based on these sub problems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Base Case 1:&lt;/strong&gt; Empty String, Empty Pattern&lt;br&gt;&lt;br&gt;
If we have an empty string and an empty pattern, that should evaluate to true. Which would look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/c146e995af5bd9d20a4964cc03ef433f/4af8e/BaseCaseOne.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vFbAAIP3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/c146e995af5bd9d20a4964cc03ef433f/4af8e/BaseCaseOne.png" alt="BaseCaseOne" title="BaseCaseOne" width="528" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Base Case 2:&lt;/strong&gt; Empty Pattern&lt;br&gt;&lt;br&gt;
If we have an empty pattern, and a non empty string, that would look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/d0e8a4632f27acb52295ecd32599f1cb/e4c9a/BaseCaseTwo.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JU-guDeS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/d0e8a4632f27acb52295ecd32599f1cb/e4c9a/BaseCaseTwo.png" alt="BaseCaseTwo" title="BaseCaseTwo" width="591" height="385"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Base Case 3:&lt;/strong&gt; Empty String&lt;br&gt;&lt;br&gt;
If we have an empty string, and a non empty pattern, that would look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/b8ac1868474c90bac7aff3c5e048b1df/0b5b1/BaseCaseThree.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--eEQNrAbJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/b8ac1868474c90bac7aff3c5e048b1df/0b5b1/BaseCaseThree.png" alt="BaseCaseThree" title="BaseCaseThree" width="593" height="387"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h5&gt;
  
  
  Iterating through
&lt;/h5&gt;

&lt;p&gt;Once our table is set up, we can start to iterate through and populate the rest of our table. Once we are done, our answer should exist in &lt;code&gt;dp[s.length][p.length]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For Dynamic Programming problems, I find it incredibly helpful to have your core logic written out ahead of time. This way as you are manually stepping through you can validate it, and make adjustments if necessary.&lt;/p&gt;

&lt;p&gt;With that said, our core logic should look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/f5a16c0353748c545cfd148b0af236b2/eac55/CoreLogic.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UG8_tMKE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/f5a16c0353748c545cfd148b0af236b2/f058b/CoreLogic.png" alt="CoreLogic" title="CoreLogic" width="630" height="349"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;DP solutions can be very unreadable sometimes when everything is being read directly from the table. I’ve added variables here to help with that. This makes things a bit more verbose but I hope that it makes it clearer.&lt;/p&gt;

&lt;p&gt;You should be able to come up with the core logic from the initial analysis of the problem. The challenging part will be figuring out where to look in the table. If you are still getting used to Dynamic Programming like I am, the best way to understand where to look is to work out a few problems. In this case I have done that ahead of time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lets start looping through:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 1
j = 1

sChar = s[i - 1] // a
pchar = p[j - 1] // a
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Notice how we are looking at the previous character. This makes things a bit more convenient to populate our table. This is because our table is taking into account the base cases which adds a character to the string and the pattern respectively.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ok, so we have a match! Lets check our DPTable to check the solution to the previous sub problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/c72f3f08af0b0ed3630f97a3a9d1020b/c7dcc/IterationOne.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--k3sN0HnL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/c72f3f08af0b0ed3630f97a3a9d1020b/f058b/IterationOne.png" alt="IterationOne" title="IterationOne" width="630" height="671"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we can see in this case, we have hit our base case, Empty String, Empty Pattern. So we can tag this cell with True.&lt;/p&gt;

&lt;p&gt;After the update our table would look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/66c8a51f1a441ebfb2a49b1719dd0ef2/68de2/IterationOneUpdate.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qn_x9_N7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/66c8a51f1a441ebfb2a49b1719dd0ef2/f058b/IterationOneUpdate.png" alt="IterationOneUpdate" title="IterationOneUpdate" width="630" height="382"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Nice!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Moving on to the next iteration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Since we don’t have any more characters in the pattern, we would move on to&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 2
p = 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is what it would look like from the table perspective:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/fb718baf39bb987296add481f572c82e/7762d/IterationTwo.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6QJj7jz0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/fb718baf39bb987296add481f572c82e/f058b/IterationTwo.png" alt="IterationTwo" title="IterationTwo" width="630" height="364"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;s[i - 1] === p[j - 1] ? 
"a" === "a" ?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have a match! Lets check our DPTable to check the solution to the previous sub problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/9f3e9a56a0a4997e95202490223d290e/1b747/IterationTwoLookBack.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--KZQPGd1K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/9f3e9a56a0a4997e95202490223d290e/f058b/IterationTwoLookBack.png" alt="IterationTwoLookBack" title="IterationTwoLookBack" width="630" height="654"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our DPTable indicates that our previous sub problem was not solved successfully. We hit our base case 2(Empty Pattern). So we would tag this cell with False.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/5c994d2c107a033c7491265c5e1992e2/1f083/IterationTwoUpdate.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YRXnYFdq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/5c994d2c107a033c7491265c5e1992e2/f058b/IterationTwoUpdate.png" alt="IterationTwoUpdate" title="IterationTwoUpdate" width="630" height="368"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;At this point we would break out from our loops, since i == 3. Our answer will exist in &lt;code&gt;dp[s.length][p.length]&lt;/code&gt; and as we can see it’s False as we expected.&lt;/p&gt;

&lt;p&gt;Nice!&lt;/p&gt;

&lt;h4&gt;
  
  
  Example Two
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/df68f778a354763e96d67e766e2f648b/10f9a/Input.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--p9PUBkIL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/df68f778a354763e96d67e766e2f648b/10f9a/Input.png" alt="Input" title="Input" width="539" height="157"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ok, working through example two, we should learn how to handle the ”*” character. Lets get started by building our table with our base cases:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/adab37cbd16f59bb8f1c342117bbe47f/78a22/DpTable.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nBOQna7d--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/adab37cbd16f59bb8f1c342117bbe47f/78a22/DpTable.png" alt="DpTable" title="DpTable" width="585" height="379"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Populating our base cases&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Base Case 1:&lt;/strong&gt; Empty Pattern, and Empty String&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/367f0a805bf56761b758ef04b6bab12d/d0d8c/DpBaseCaseOne.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4V0rD_Rn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/367f0a805bf56761b758ef04b6bab12d/d0d8c/DpBaseCaseOne.png" alt="DpBaseCaseOne" title="DpBaseCaseOne" width="609" height="375"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Base Case 2:&lt;/strong&gt; Empty String&lt;/p&gt;

&lt;p&gt;How does an empty string match with a single ”*” pattern?&lt;/p&gt;

&lt;p&gt;Remembering the definition of ”*”, we can match zero or more of the preceding character. Since our base case is an empty string it eliminates the option of matching one or more of the preceding character. That leaves us with matching zero characters. To do that we would look at the value in &lt;code&gt;dp[i][j - 2]&lt;/code&gt; which is our base case (Empty String, Empty Pattern). So we would tag this cell with True.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;We will have to remember to add this logic when building our base cases&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/5a20ab2a096df2d23e3d2239b7e0e02e/30d16/DpBaseCaseTwo.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Q2a25Yb2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/5a20ab2a096df2d23e3d2239b7e0e02e/f058b/DpBaseCaseTwo.png" alt="DpBaseCaseTwo" title="DpBaseCaseTwo" width="630" height="683"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It’s easy to get tripped up on this piece, I sure did! Let’s dive a little deeper to make sure that this makes sense by looking at an example.&lt;/p&gt;

&lt;p&gt;The pattern “a*” is looking to match strings that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Have one or more “a”s&lt;/li&gt;
&lt;li&gt;Have zero “a”s&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Empty strings, have zero “a”s. So this checks out.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Tip: Dive deeper when you get tripped up. Understanding the details will set you up for success. Brushing over them could leave you blind sided in the next steps!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Base Case 3:&lt;/strong&gt; Empty Pattern&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/98f7c1b9bd81b838cb7fe401584428fd/39c09/DpBaseCaseThree.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--CbzGhpFN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/98f7c1b9bd81b838cb7fe401584428fd/39c09/DpBaseCaseThree.png" alt="DpBaseCaseThree" title="DpBaseCaseThree" width="624" height="373"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Nice, table is ready!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration One&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Starting point will be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 1
j = 1 

s[i - 1] === p[j - 1] ? 
"a" === "a"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have a match. Lets check our DPTable to check the solution to the previous sub problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/f8f79cc984e481acb4e0ebbe1c1e9ae9/aec65/DpIterationOne.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bre_9rac--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/f8f79cc984e481acb4e0ebbe1c1e9ae9/f058b/DpIterationOne.png" alt="DpIterationOne" title="DpIterationOne" width="630" height="725"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we can see we hit our base case 1 (Empty String, Empty Pattern). We can tag this cell with True.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration Two&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 1
j = 2

s[i - 1] === p[j - 1] ? 
"a" === "*"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our first star case! Lets check our DPTable to check the solution to the previous sub problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/61358b0383967fe2d0777bd4fab737af/7131f/DpIterationTwo.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3NHin2Em--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/61358b0383967fe2d0777bd4fab737af/f058b/DpIterationTwo.png" alt="DpIterationTwo" title="DpIterationTwo" width="630" height="676"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this case we can see that &lt;code&gt;matchZero&lt;/code&gt; hits our base case 2 (Empty Pattern), which is not a successful solution.&lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;previousCharMatch&lt;/code&gt; is true, we can explore &lt;code&gt;matchingOneOrMore&lt;/code&gt; which was solved successfully. So we can tag with cell with True.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration Three&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 2
j = 1

s[i - 1] === p[j - 1] ? 
"a" === "a"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have a match. Lets check our DPTable to check the solution to the previous sub problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/278f1c8f987e0321e4d8ec8f4cded96c/748f4/DpIterationThree.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--maN5TAb7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/278f1c8f987e0321e4d8ec8f4cded96c/f058b/DpIterationThree.png" alt="DpIterationThree" title="DpIterationThree" width="630" height="725"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We would tag this cell with False since we hit base case 3 (Empty Pattern).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration Four&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 2
j = 2

s[i - 1] === p[j - 1] ? 
"a" === "*"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;”*” Pattern again! Lets check our DPTable to check the solution to the previous sub problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/a46a5efebc0419b6ee94f8c95122c415/160a3/DpIterationFour.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--uAQwuyVa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/a46a5efebc0419b6ee94f8c95122c415/f058b/DpIterationFour.png" alt="DpIterationFour" title="DpIterationFour" width="630" height="677"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Just like Iteration Two:&lt;/p&gt;

&lt;p&gt;We can see that &lt;code&gt;matchZero&lt;/code&gt; hits our base case 2 (Empty Pattern), which is not a successful solution.&lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;previousCharMatch&lt;/code&gt; is true, we can explore &lt;code&gt;matchingOneOrMore&lt;/code&gt; which was solved successfully. So we can tag with cell with True.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Final Table&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Our final table will look like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/1a2f795aec50dae970329fe20394d405/d4713/DpFinalTable.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cAmvpJZO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/1a2f795aec50dae970329fe20394d405/d4713/DpFinalTable.png" alt="DpFinalTable" title="DpFinalTable" width="531" height="390"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our answer will be in &lt;code&gt;dp[s.length][p.length]&lt;/code&gt;, and as we can see it’s True as expected.&lt;/p&gt;

&lt;p&gt;Nice!&lt;/p&gt;

&lt;h4&gt;
  
  
  Example 3
&lt;/h4&gt;

&lt;p&gt;I’ll leave it to you to work out example three. You should follow the same pattern we did in the previous two examples. The new character you will have to account for is ”.” which matches any single character once.&lt;/p&gt;

&lt;p&gt;The best way to do this is to have the core logic available, and step through populating the table cell by cell. This is precisely what our algorithm will do. A solid understanding of this process will make implementing the algorithm a breeze!&lt;/p&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;Solve with Dynamic Programming&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create DP table. Matrix of s.length + 1 by p.length + 1. Initialize with false values.&lt;/li&gt;
&lt;li&gt;Populate base cases

&lt;ul&gt;
&lt;li&gt;Empty String, Empty Pattern&lt;/li&gt;
&lt;li&gt;Empty String&lt;/li&gt;
&lt;li&gt;Empty Pattern&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Write nested for loop

&lt;ul&gt;
&lt;li&gt;Outer loop starting from 1 &amp;lt;= s.length&lt;/li&gt;
&lt;li&gt;Inner loop starting from 1 &amp;lt;= p.length&lt;/li&gt;
&lt;li&gt;In each iteration

&lt;ul&gt;
&lt;li&gt;If we have match&lt;/li&gt;
&lt;li&gt;Check the previous string so far at &lt;code&gt;dp[i - 1][j - 1]&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;If the previous is True, tag this cell as True&lt;/li&gt;
&lt;li&gt;If we have a ”*”&lt;/li&gt;
&lt;li&gt;MatchZero: &lt;code&gt;dp[i][j - 2]&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;If PreviousMatchChar

&lt;ul&gt;
&lt;li&gt;MatchZero or MatchOneOrMore: &lt;code&gt;dp[i - 1][j]&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;If either of these is True tag the cell as True. Otherwise False&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Once you break from the loop return &lt;code&gt;dp[s.length][p.length]&lt;/code&gt; for the solution&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const array = (n) =&amp;gt; { return Array(n).fill(false); }

const isMatch = (s, p) =&amp;gt; {

    // Adding one to account for base cases
    const dp = array(s.length + 1).map(() =&amp;gt; array(p.length + 1));

    // Base cases
    // Empty String Empty Pattern
    dp[0][0] = true;

    // Empty String
    for(let i = 1; i &amp;lt;= p.length; i++) {
        let pChar = p[i - 1];
        if (pChar === "*") {
            dp[0][i] = dp[0][i - 2];
        }
    }

    // Empty Pattern
    // We handle this by pre populating our matrix with false values

    // Iteration
    for(let i = 1; i &amp;lt;= s.length; i++) {
        for(let j = 1; j &amp;lt;= p.length; j++) {
            let sChar = s[i - 1];
            let pChar = p[j - 1];
            let stringMatchSoFar = dp[i - 1][j - 1];
            let currentMatch = sChar === pChar || pChar === ".";
            if (currentMatch) {
                dp[i][j] = stringMatchSoFar;
            }

            if (pChar === '*') {
                let matchZero = dp[i][j - 2];
                let previousMatch = sChar === p[j - 2] || p[j - 2] === ".";
                let matchOneOrMore = dp[i - 1][j];
                dp[i][j] = matchZero || (previousMatch &amp;amp;&amp;amp; matchOneOrMore);
            }
        }
    }

    return dp[s.length][p.length];
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;The time complexity of this algorithm is O(S * P) where S is the length of the string and P is the length of the pattern. The space complexity will be O(S * P) since we are storing solutions to sub problems in a matrix. Although Dynamic Programming solutions can be hard to think about the time complexity analysis is quite simple as you can see.&lt;/p&gt;

&lt;p&gt;Key takeaways:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Lay out your core logic ahead of time&lt;/li&gt;
&lt;li&gt;Build your DP table manually by stepping through the problem and test your core logic&lt;/li&gt;
&lt;li&gt;Make adjustments to your core logic as needed as you step through&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Once your core logic is solid, the rest of the implementation is fairly trivial as you can see.&lt;/p&gt;

&lt;p&gt;Hope you found this helpful!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 10. Regular Expression Matching</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sun, 03 Apr 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-10-regular-expression-matching-3eem</link>
      <guid>https://dev.to/vickdayaram/leetcode-10-regular-expression-matching-3eem</guid>
      <description>&lt;p&gt;Solving LeetCode 10, Regular Expression Matching. &lt;a href="https://leetcode.com/problems/regular-expression-matching/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;Given an input string s and a pattern p, implement regular expression matching with support for ’.’ and ’*’ where:&lt;/p&gt;

&lt;p&gt;’.’ Matches any single character.​​​​ ’*’ Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Thoughts
&lt;/h3&gt;

&lt;p&gt;Hard problem… What pattern can we apply to solve this?&lt;/p&gt;

&lt;h3&gt;
  
  
  Breaking it down
&lt;/h3&gt;

&lt;p&gt;Lets start breaking this down piece by piece, and looking at the examples.&lt;/p&gt;

&lt;h4&gt;
  
  
  Example 1:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/093874041516b67e8b2a91af6fab974d/7a1fb/example-1-start.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BtolBiqo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/093874041516b67e8b2a91af6fab974d/f058b/example-1-start.png" alt="example 1 start" title="example 1 start" width="630" height="234"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How can we approach this? We can iterate through and compare the characters. If they are equal, we can compare the next set of characters and so on.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/2cc19faecb8df6fc5741a4657b0796de/6937a/example-1-start-iterate.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QljOeXUZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/2cc19faecb8df6fc5741a4657b0796de/f058b/example-1-start-iterate.png" alt="example 1 start iterate" title="example 1 start iterate" width="630" height="233"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In this example, we run out of characters for the pattern but still have characters in the string. This scenario indicates we don’t have a match. This is the case because we are looking for a full match, not partial.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h5&gt;
  
  
  Takeaway
&lt;/h5&gt;

&lt;p&gt;Once we reach the end of the pattern, we can check the length of the remaining string. If it equals zero, we have a match. Otherwise, we do not.&lt;/p&gt;

&lt;h4&gt;
  
  
  Example 2:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/3d43e9513f906ed8d8028fbb1859d803/d9199/example-2-start.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--M7P8eBZY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/3d43e9513f906ed8d8028fbb1859d803/f058b/example-2-start.png" alt="example 2 start" title="example 2 start" width="630" height="214"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling ”*”
&lt;/h5&gt;

&lt;p&gt;After walking through this example we should understand how to handle the case with ”*” in the pattern.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Definition of ”*”: Matches zero or more of the preceding character in the pattern.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Reading the definition tells us we can match in two ways.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We can have zero occurrences of the preceding character in the pattern&lt;/li&gt;
&lt;li&gt;We can have one or more occurrences of the preceding character in the pattern&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The solution could exist in option one, or option two. We would have to explore both to know for sure.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: Whenever we run into problems where we need to explore multiple paths, recursion can be an effective tool. Uncovering this indicates that we could use recursion to solve this, and that’s what we will be doing. If you are not familiar with recursion, I’d recommend to learn the pattern first and then come back to this post.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h5&gt;
  
  
  Stepping through the example
&lt;/h5&gt;

&lt;p&gt;With recursion in mind, lets work through the example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/3d43e9513f906ed8d8028fbb1859d803/d9199/example-2-start.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--M7P8eBZY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/3d43e9513f906ed8d8028fbb1859d803/f058b/example-2-start.png" alt="example 2 start" title="example 2 start" width="630" height="214"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can compare the first characters and see that they are equal.&lt;/p&gt;

&lt;p&gt;To identify if we have the ”*” we have to look ahead to the next character in “p”. If it’s a ”*” we need to handle both our options.&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The First Case (Level 1)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case one&lt;/strong&gt; : Zero occurrences&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Ignore the characters in “p” and skip ahead&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/3a7ddef85d11f582a1f3a7ea67df3794/99661/example-2-skipping-ahead.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pqQZP2DG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/3a7ddef85d11f582a1f3a7ea67df3794/f058b/example-2-skipping-ahead.png" alt="example 2 skipping ahead" title="example 2 skipping ahead" width="630" height="186"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since we have reached the end of the pattern, but not the string, we would return false&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The Second Case (Level 1)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case two&lt;/strong&gt; : One or more occurrences of the preceding character&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Move on to check the next character in “s”&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/1d70c92531b2eaba7afb637daf8cd9a7/62a6a/example-2-next-char.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1E54AJjN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/1d70c92531b2eaba7afb637daf8cd9a7/f058b/example-2-next-char.png" alt="example 2 next char" title="example 2 next char" width="630" height="173"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once we get here, we would compare the characters again. Since they match, and the next character in p is ”*”, we would explore our two cases again.&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The First Case (Level 2)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case one&lt;/strong&gt; : Zero occurrences&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Ignore the characters in “p” and skip ahead&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/8d54449ad705a7fe3161fbf60469b919/8740f/example-2-skipping-ahead-2.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BGK3KvUO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/8d54449ad705a7fe3161fbf60469b919/f058b/example-2-skipping-ahead-2.png" alt="example 2 skipping ahead 2" title="example 2 skipping ahead 2" width="630" height="199"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We would jump ahead in “p”, but we would still have characters left in “s”. So this would evaluate to false.&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The Second Case (Level 2)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case two&lt;/strong&gt; : One or more occurrences of the preceding character&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Move on to check the next character in “s”&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/1832b85ff65f68b32332e4a5b4a5cab9/2bef9/example-2-next-char-2.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zzPl1hX3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/1832b85ff65f68b32332e4a5b4a5cab9/f058b/example-2-next-char-2.png" alt="example 2 next char 2" title="example 2 next char 2" width="630" height="229"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We would jump ahead in “s” and reach the end of “s”. We would still have characters in “p” however. So, once again, we would check the next character in “p”, identify the ”*” case, and explore the two cases. Deeper in the stack we go!&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The First Case (Level 3)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case one&lt;/strong&gt; : Zero occurrences&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Ignore the characters in “p” and skip ahead&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/f4bd83cc42755b92cf7808a34bcb24dd/72aae/example-2-skipping-ahead-3.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VMfgDvQA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/f4bd83cc42755b92cf7808a34bcb24dd/f058b/example-2-skipping-ahead-3.png" alt="example 2 skipping ahead 3" title="example 2 skipping ahead 3" width="630" height="216"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This time, we have reached the end of both strings, which means that we have a match, and would evaluate to true.&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The Second Case (Level 3)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case two&lt;/strong&gt; : One or more occurrences of the preceding character&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Move on to check the next character in “s”&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/0a3f92b59d1e013fe52d15a7001896a0/12bff/example-2-next-char-3.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--O6QQ4Yc3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/0a3f92b59d1e013fe52d15a7001896a0/f058b/example-2-next-char-3.png" alt="example 2 next char 3" title="example 2 next char 3" width="630" height="195"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here we would move ahead in s, and be out of bounds. Since there is no character to compare here we would return false.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: We are exploring this case for completeness, but depending on how we implement our algorithm we could just stop exploring once we find a true case.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h5&gt;
  
  
  Takeaway
&lt;/h5&gt;

&lt;p&gt;Recursion will be a good approach to solve this since we have to explore two possible paths.&lt;/p&gt;

&lt;h4&gt;
  
  
  Example 3
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/93606fcc8f339a7cedcc3e0baaff2dde/d8817/example-3-start.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--L20gID5f--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/93606fcc8f339a7cedcc3e0baaff2dde/f058b/example-3-start.png" alt="example 3 start" title="example 3 start" width="630" height="231"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For this example we have ”.” This character indicates that we can match any character. In this case it’s followed by the ”*” so we would apply the cases we learned in the last example as well.&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The First Case (Level 1)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case one&lt;/strong&gt; : Zero occurrences&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Ignore the characters in “p” and skip ahead&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/1ab52136825ad039e8274a328019bab9/73caa/example-3-skipping-ahead.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--L9fKF5Y4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/1ab52136825ad039e8274a328019bab9/f058b/example-3-skipping-ahead.png" alt="example 3 skipping ahead" title="example 3 skipping ahead" width="630" height="213"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this case we would run out of characters in “p”, but we would still have characters in “s”. So this case would evaluate to false&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The Second Case (Level 1)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case two&lt;/strong&gt; : One or more occurrences of the preceding character&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Move on to check the next character in “s”&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/78d086f1daa976a98e950aa4a44e816a/04784/example-3-next-char.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QfIOOhDX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/78d086f1daa976a98e950aa4a44e816a/f058b/example-3-next-char.png" alt="example 3 next char" title="example 3 next char" width="630" height="239"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since ”.” can equal any character, we would move ahead to the next character in “s”. From there we would evaluate our two cases again.&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The First Case (Level 2)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case one&lt;/strong&gt; : Zero occurrences&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Ignore the characters in “p” and skip ahead&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/4eee62e5d656c62c7ab067382f87bbc7/077b7/example-3-skipping-ahead-2.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pKCbAun0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/4eee62e5d656c62c7ab067382f87bbc7/f058b/example-3-skipping-ahead-2.png" alt="example 3 skipping ahead 2" title="example 3 skipping ahead 2" width="630" height="211"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Like before, this would evaluate to false since we have ran out of characters in “p”.&lt;/p&gt;

&lt;h5&gt;
  
  
  Handling The Second Case (Level 2)
&lt;/h5&gt;

&lt;p&gt;&lt;strong&gt;Case two&lt;/strong&gt; : One or more occurrences of the preceding character&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Action&lt;/strong&gt; : Move on to check the next character in “s”&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/a31748c29a8f6026d8e0793ef1c32e84/d56e1/example-3-next-char-2.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--SFGEzE7N--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/a31748c29a8f6026d8e0793ef1c32e84/f058b/example-3-next-char-2.png" alt="example 3 next char 2" title="example 3 next char 2" width="630" height="221"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This case looks familiar from the previous example. We would move one character ahead in “s” since ”.” matches any character. Once we get here, we can see that we will eventually evaluate to true, by exploring case number one: zero occurrences of the preceding character in the next level of the stack.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Nice! Stepping through these examples have helped us understand the cases we will have to handle. Now that we have a good understanding of the problem, lets lay our thoughts out so we can code it up.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;Like we uncovered we will be using a recursive approach to solve the problem. With that in mind, lets identify our base cases&lt;/p&gt;

&lt;p&gt;Bases Cases:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If we reach the end of “p” and the end of “s” we have a match&lt;/li&gt;
&lt;li&gt;Evaluate firstMatch: Check if the first characters in “s” and “p” equal&lt;/li&gt;
&lt;li&gt;Check if the next character in “p” is a ”*”, if so:

&lt;ul&gt;
&lt;li&gt;Return&lt;/li&gt;
&lt;li&gt;Case one: call the function by moving “p” ahead by two characters&lt;/li&gt;
&lt;li&gt;OR&lt;/li&gt;
&lt;li&gt;Case two: firstMatch AND call the function by moving “s” ahead by one character&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Return

&lt;ul&gt;
&lt;li&gt;firstMatch&lt;/li&gt;
&lt;li&gt;AND&lt;/li&gt;
&lt;li&gt;call the function by moving “s” up on character and “p” up one character&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const isMatch = (s, p, sIdx = 0, pIdx = 0) =&amp;gt; {
    if (p.length === pIdx) {
        return s.length === sIdx;
    }

    const firstMatch = sIdx &amp;lt; s.length &amp;amp;&amp;amp; (s[sIdx] === p[pIdx] || p[pIdx] === ".");

    if ((pIdx + 1) &amp;lt; p.length &amp;amp;&amp;amp; p[pIdx + 1] === "*") {
        return (
            isMatch(s, p, sIdx, pIdx + 2) // Case One
            || firstMatch &amp;amp;&amp;amp; isMatch(s, p, sIdx + 1, pIdx) // Case Two
        )
    }

    return firstMatch &amp;amp;&amp;amp; isMatch(s, p, sIdx + 1, pIdx + 1);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;In the worst case, this algorithm runs in O((S + P) * 2^S + P/2), where S and P are the lengths of “s” and “p” respectively. This time complexity is very challenging to pin down. I’d recommend this &lt;a href="https://levelup.gitconnected.com/solving-for-recursive-complexity-736439987cb0"&gt;blog post&lt;/a&gt; for a deep dive.&lt;/p&gt;

&lt;p&gt;Working through this problem recursively is helpful to understand what is involved in figuring out the solution. However, the optimal solution to this problem can be achieved with Dynamic Programming. The Dynamic Programming solution to this problem will run in O(S * P), which is much faster.&lt;/p&gt;

&lt;p&gt;If you are not familiar with Dynamic Programming it can be hard to wrap your head around at first. However, once you understand how to apply the pattern, it can help you come up with performant solutions with minimal code. It’s a very powerful pattern.&lt;/p&gt;

&lt;p&gt;I’d challenge you to take what we have learned and try to solve this problem with Dynamic Programming. I’ll challenge my self with that too!&lt;/p&gt;

&lt;p&gt;Hope this was helpful!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 102. Binary Tree Level Order Traversal</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sun, 20 Mar 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-102-binary-tree-level-order-traversal-3cj2</link>
      <guid>https://dev.to/vickdayaram/leetcode-102-binary-tree-level-order-traversal-3cj2</guid>
      <description>&lt;p&gt;Solving LeetCode 102. Binary Tree Level Order Traversal. &lt;a href="https://leetcode.com/problems/binary-tree-level-order-traversal/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;Example 1 Image:&lt;a href="https://www.deepdevblog.com/static/02ac3d75217af49148c18279c63b9204/d0cc0/LeetCodeExample1.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--604ISFzq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/02ac3d75217af49148c18279c63b9204/f058b/LeetCodeExample1.png" alt="LeetCodeExample1" title="LeetCodeExample1" width="630" height="615"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2:
Input: root = [1]
Output: [[1]]

Example 3: 
Input: root = []
Output: []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Thoughts
&lt;/h3&gt;

&lt;p&gt;Breadth First Search!&lt;/p&gt;

&lt;h3&gt;
  
  
  Breaking it down
&lt;/h3&gt;

&lt;p&gt;We can use BFS to traverse the tree and collect all the nodes for a given level in a currentLevel array. We can store each of our currentLevel arrays in an results array. Once we finish our traversal our solution should be contained in results.&lt;/p&gt;

&lt;p&gt;If your not familiar with how to implement BFS, continue to read on here. We’ll describe BFS implementation as it relates to this problem. If you are familiar feel free to skip.&lt;/p&gt;

&lt;h4&gt;
  
  
  Implementing BFS
&lt;/h4&gt;

&lt;p&gt;We can use a queue, while loop, and for loop to implement BFS. Typically a queue and a while loop are required, however the for loop is optional depending on the problem. Also, remember this is just one way to do this.&lt;/p&gt;

&lt;p&gt;To kick things off we will initialize a queue with the root node. We will continue to iterate through the queue while it’s not empty.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/8e427a739bad09aaddb3340b846915ab/c483d/BfsStartingPoint.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3KDnL-BJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/8e427a739bad09aaddb3340b846915ab/f058b/BfsStartingPoint.png" alt="BfsStartingPoint" title="BfsStartingPoint" width="630" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we iterate in our while loop we will capture the current length of the queue. This length represents the number of nodes at the current level. Looking at our example, for the first iteration currentLength will equal one. The next time it will equal two, and the last iteration it will equal two again. This will become more clear as we continue to work through the problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/61c2c927c724f7ffcf3051537300c047/a8a6f/BfsCurrentLength.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--24CuvrSn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/61c2c927c724f7ffcf3051537300c047/f058b/BfsCurrentLength.png" alt="BfsCurrentLength" title="BfsCurrentLength" width="630" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Storing currentLength is critical here. That’s the information that lets us know the bounds of each level so we can operate on nodes on a level by level fashion.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Important Note. Make sure to save currentLevel as a variable, and don’t use queue.length. As you will see we are always adding child nodes to the queue so the length will change.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Every node we grab in the for loop will belong to the currentLevel. For this problem we are asked to collect each level and return it in an array. So every time we shift() from our queue, we can push the value to the currentLevel.&lt;/p&gt;

&lt;p&gt;To collect the next level, we will check if the current node has children. If it does, we will push them to the queue.&lt;/p&gt;

&lt;p&gt;Once the iteration finishes, our queue should have the next level and our result should have the first level.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/1df4f96b161c34b991e128ce1b1365af/166a3/BfsSecondIteration.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Jcq6NaKV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/1df4f96b161c34b991e128ce1b1365af/f058b/BfsSecondIteration.png" alt="BfsSecondIteration" title="BfsSecondIteration" width="630" height="319"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Following these steps, we will collect all the levels! Nice.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;Approach Overview&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If there is no root, return []&lt;/li&gt;
&lt;li&gt;Initialize a queue with the root node&lt;/li&gt;
&lt;li&gt;Initialize a results array&lt;/li&gt;
&lt;li&gt;While the queue is not empty

&lt;ul&gt;
&lt;li&gt;Initialize a currentLevel array&lt;/li&gt;
&lt;li&gt;Capture the currentLength of the queue&lt;/li&gt;
&lt;li&gt;Declare a for loop, and iterate through the queue from 0 to the currentLength&lt;/li&gt;
&lt;li&gt;Shift() from the queue&lt;/li&gt;
&lt;li&gt;If node.left, push node.left to the queue&lt;/li&gt;
&lt;li&gt;If node.right, push node.right to the queue&lt;/li&gt;
&lt;li&gt;push node.val to the currentLevel&lt;/li&gt;
&lt;li&gt;push currentLevel to results&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Return results&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const levelOrder = (root) =&amp;gt; {

    if (!root) return []

    const results = [];
    const queue = [root];

    while (queue.length &amp;gt; 0) {
        const currentLength = queue.length;
        const currentLevel = [];

        for(let i = 0; i &amp;lt; currentLength; i++) {
            const node = queue.shift();
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
            currentLevel.push(node.val);
        }

        results.push(currentLevel);
    }

    return results;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;The time complexity of this Algorithm is O(N) since we are visiting every node in the tree. The space complexity will be O(N) + O(K), where K is the level with the most nodes. This represents the biggest size that our queue could be.&lt;/p&gt;

&lt;p&gt;Another interesting piece here is the queue that we are using. In my solution I am just using a normal JS array. This works like a queue in terms of the operations, but does not give us the performance we could get from a true queue implementation. Analyzing this piece is beyond the scope of this blog post, but it’s important to call it out.&lt;/p&gt;

&lt;p&gt;Hope you found this helpful!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 25. Reverse Nodes in k-Group</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sun, 27 Feb 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-25-reverse-nodes-in-k-group-4ekj</link>
      <guid>https://dev.to/vickdayaram/leetcode-25-reverse-nodes-in-k-group-4ekj</guid>
      <description>&lt;p&gt;Solving LeetCode 25. Reverse Nodes in k-Group. &lt;a href="https://leetcode.com/problems/reverse-nodes-in-k-group/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.&lt;/p&gt;

&lt;p&gt;k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.&lt;/p&gt;

&lt;p&gt;You may not alter the values in the list’s nodes, only nodes themselves may be changed.&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Thoughts
&lt;/h3&gt;

&lt;p&gt;Linked Lists… For me, these problems are fairly easy to understand conceptually. The challenging part here is figuring out the implementation. With Linked Lists problems, keeping track of pointers is key.&lt;/p&gt;

&lt;h3&gt;
  
  
  Breaking it down
&lt;/h3&gt;

&lt;p&gt;Lets look at an example and start working through it to understand what the implementation will look like.&lt;/p&gt;

&lt;h4&gt;
  
  
  Overview
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/ac7aa95a9090c0a6af0153c384e7ae85/df56e/example.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hnRyj4jm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/ac7aa95a9090c0a6af0153c384e7ae85/f058b/example.png" alt="example" title="example" width="630" height="279"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From looking at this we can see that we will need a way to count the nodes as we iterate through them. Once we get to k nodes, we will have to run some operations to reverse that sub list, and re-connect it. Once we do that, we can move on to the next k nodes.&lt;/p&gt;

&lt;h4&gt;
  
  
  What to do once you get to k nodes
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/b52fbbee58c837d01e6d5790e8a3d6bd/636d3/firstIteration.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ulcu3Ydv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/b52fbbee58c837d01e6d5790e8a3d6bd/f058b/firstIteration.png" alt="firstIteration" title="firstIteration" width="630" height="306"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once we get to the kth node we will need to reverse the list from 1 to 2. In order to reverse a list, we will need the startingNode. We will need a pointer to keep track of that.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/072b9e16dccf505845146fc795498910/cd78c/firstIterationStartingNode.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OPf9I5Z7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/072b9e16dccf505845146fc795498910/f058b/firstIterationStartingNode.png" alt="firstIterationStartingNode" title="firstIterationStartingNode" width="630" height="304"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then we can disconnect the list, and keep track of the rightHalf to re-connect.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/48c5e186af3acef911888b0728e2df9b/d43b4/firstIterationRightPart.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--eRRSRB3a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/48c5e186af3acef911888b0728e2df9b/f058b/firstIterationRightPart.png" alt="firstIterationRightPart" title="firstIterationRightPart" width="630" height="362"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Reversing the sub-list
&lt;/h4&gt;

&lt;p&gt;Now we can actually reverse the list. We won’t be doing a deep dive on linkedList reversal here. If you aren’t familiar with how to reverse a linkedList, I highly recommend you learn that first before diving into this problem.&lt;/p&gt;

&lt;p&gt;Once we reverse the list we should have:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/010b41a57ed0ed675a0703c193616635/e8e04/firstIterationReverseTheList.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fdGlBmLd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/010b41a57ed0ed675a0703c193616635/f058b/firstIterationReverseTheList.png" alt="firstIterationReverseTheList" title="firstIterationReverseTheList" width="630" height="347"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Important observation here. Notice how starting node is now the tail of our subList, and currentNode is the head.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;
  
  
  Re-connecting the reversed sub-list to the main list and re-setting for the next iteration
&lt;/h4&gt;

&lt;p&gt;To re-connect and reset we would run the following operations on our pointers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;startingNode.next = rightPart
startingNode = rightPart
currentNode = rightPart
counter = 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Resulting in:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/e603e35ca7f75358c72fa255c23131b8/fbf76/firstIterationResetForNext.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dysS5kgM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/e603e35ca7f75358c72fa255c23131b8/f058b/firstIterationResetForNext.png" alt="firstIterationResetForNext" title="firstIterationResetForNext" width="630" height="386"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Hmm ok, we have made some progress. There are two things that we are missing here though…&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ol&gt;
&lt;li&gt;What about the leftPart?!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We haven’t seen the leftPart come into action yet, but as you probably guessed we will have to handle this. To handle this we will use a leftPart pointer.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What are we going to return once we are done?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We will have to return the newHead of the first subList. To handle this, we can… you guessed it, use a newHead pointer.&lt;/p&gt;

&lt;h4&gt;
  
  
  Re-connecting the reversed sub-list to the main list and re-setting for the next iteration with the leftPart and newHead
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/eba82e70b031920ceac72279b89e42af/e8814/firstIterationLeftPartNewHead.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EwELX06d--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/eba82e70b031920ceac72279b89e42af/f058b/firstIterationLeftPartNewHead.png" alt="firstIterationLeftPartNewHead" title="firstIterationLeftPartNewHead" width="630" height="377"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, we’ll run the following operations…&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;startingNode.next = rightPart // connect the list
newHead = currentNode // set the newHead, we will only do this once
leftPart = startingNode // save the leftPart for the next iteration
startingNode = rightPart // save the next startingNode
currentNode = rightPart // set up the next currentNode
counter = 1 // reset the counter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we’ll be left with…&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/55d12dcf2e2f99ab2e6e661c78db0870/bc3ae/firstIterationComplete.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TstQylUU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/55d12dcf2e2f99ab2e6e661c78db0870/f058b/firstIterationComplete.png" alt="firstIterationComplete" title="firstIterationComplete" width="630" height="419"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Re-connecting the reversed sub-list to the main list and re-setting for the next iteration in the middle of the list
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/9ecd9e749730346837297232bc3a0b6c/04784/secondIteration.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--98boSG4C--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/9ecd9e749730346837297232bc3a0b6c/f058b/secondIteration.png" alt="secondIteration" title="secondIteration" width="630" height="456"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Disconnect the subList, and reverse it by running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rightPart = currentNode.next // save the rightPart
currentNode.next = null, disconnect from the main list
reverse(startingNode) // reverse the subList
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Resulting in…&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/781bc038080a1bdbe11a41f6d49c1992/0d98f/secondIterationReverseSublist.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UwAity0b--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/781bc038080a1bdbe11a41f6d49c1992/f058b/secondIterationReverseSublist.png" alt="secondIterationReverseSublist" title="secondIterationReverseSublist" width="630" height="418"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Re-connect the subList to the mainList, and reset for the next iteration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;leftPart.next = currentNode // connect the leftPart
startingNode.next = rightPart // connect the rightPart
leftPart = startingNode // set the next leftPart
startingNode = rightPart // set the next startingNode
currentNode = rightPart // set the next currentNode
counter = 1 // reset the counter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Resulting in…&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/0e565de38483a2f3afe147ff31155c61/37048/secondIterationComplete.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--G3oN8GuM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/0e565de38483a2f3afe147ff31155c61/f058b/secondIterationComplete.png" alt="secondIterationComplete" title="secondIterationComplete" width="630" height="383"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Nice, our process should handle all the intermediate subLists.&lt;/p&gt;

&lt;h4&gt;
  
  
  Handling the end of the list
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/c378a01084f38b3f703fc7adef705805/0786c/lastIteration.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--KH108qCe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/c378a01084f38b3f703fc7adef705805/f058b/lastIteration.png" alt="lastIteration" title="lastIteration" width="630" height="383"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here our counter equals 2 which equals k. With our current flow this would trigger our a subList reversal, however it shouldn’t since this is not a true subList with length 2. To handle this case, we will only trigger our process if:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (currentNode !== null &amp;amp;&amp;amp; counter === k)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Adding this will ensure that we get the desired behavior. Nice!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/625743cbdcc25dfa8cfda7b634a8b4a8/a5c09/highFiveDog.jpg"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mHVQFbtg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/625743cbdcc25dfa8cfda7b634a8b4a8/828fb/highFiveDog.jpg" alt="highFiveDog" title="highFiveDog" width="630" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Edge case handling&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If k === 1, return head. (Nothing needs to be processed in this case, return the list as is)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Global variables&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Declare leftPart initialize to null&lt;/li&gt;
&lt;li&gt;Declare newHead initialize to null&lt;/li&gt;
&lt;li&gt;Declare currentNode initialize to head&lt;/li&gt;
&lt;li&gt;Declare startingNode initialize to head&lt;/li&gt;
&lt;li&gt;Declare counter initialize to 1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Main loop&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Iterate through the list while currentNode !== null&lt;/li&gt;
&lt;li&gt;Increment the counter in each iteration&lt;/li&gt;
&lt;li&gt;If the counter === k and currentNode !== null

&lt;ul&gt;
&lt;li&gt;Declare rightPart, and initialize it to currentNode.next for next iteration&lt;/li&gt;
&lt;li&gt;Disconnect and reverse&lt;/li&gt;
&lt;li&gt;Set currentNode.next to null to disconnect the list&lt;/li&gt;
&lt;li&gt;Reverse the list from the startingNode&lt;/li&gt;
&lt;li&gt;If there is no head, set it to currentNode&lt;/li&gt;
&lt;li&gt;Re connect&lt;/li&gt;
&lt;li&gt;Connect to left: If there is a leftPart, connect it to currentNode&lt;/li&gt;
&lt;li&gt;Connect to right: Set startingNode.next to rightPart&lt;/li&gt;
&lt;li&gt;Re set for next iteration&lt;/li&gt;
&lt;li&gt;Set leftPart to startingNode&lt;/li&gt;
&lt;li&gt;Set startingNode to rightPart&lt;/li&gt;
&lt;li&gt;Set currentNode to rightPart&lt;/li&gt;
&lt;li&gt;Set counter to 1&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Return newHead&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lets code it up!&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const reverseKGroup = (head, k) =&amp;gt; {

    // Handle edge case
    if (k === 1) {
        return head;
    }

    let leftPart = null;
    let newHead = null;
    let currentNode = head;
    let startingNode = head;
    let counter = 1;

    while (currentNode) {
        currentNode = currentNode.next;
        counter++;
        if (currentNode &amp;amp;&amp;amp; counter === k) {

            // Save right part for next iteration    
            let rightPart = currentNode.next;

            // Disconnect and reverse
            currentNode.next = null;
            reverse(startingNode);

            // Set newHead if needed
            if (newHead === null) {
                newHead = currentNode;
            }

            // Connect the list back
            if (leftPart !== null) {
                leftPart.next = currentNode;
            } 
            startingNode.next = rightPart;

            // Reset for the next iteration
            leftPart = startingNode;
            startingNode = rightPart;
            currentNode = rightPart;
            counter = 1;
        }
    }

    return newHead;
}

const reverse = (node) =&amp;gt; {
    let prev = null;
    let currentNode = node;
    while (currentNode) {
        let nextNode = currentNode.next;
        currentNode.next = prev;
        prev = currentNode;
        currentNode = nextNode;
    }
    return prev; // returning for as a good practice, not needed in this problem
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;This algorithm runs in O(n) time where n is the number of nodes in the list, and O(1) space.&lt;/p&gt;

&lt;p&gt;As you can see the code is fairly trivial. It’s very easy to get tripped up with all the different pointers that you have to keep track of. I sure did!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Having a good mental model is key, and drawing things out really helps especially if your more visually inclined. In fact, I’d say that’s probably true for most problems.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hope this was helpful!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 57. Insert Interval</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sun, 20 Feb 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-57-insert-interval-4jg7</link>
      <guid>https://dev.to/vickdayaram/leetcode-57-insert-interval-4jg7</guid>
      <description>&lt;p&gt;Solving LeetCode 57, Insert Interval. &lt;a href="https://leetcode.com/problems/insert-interval/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.&lt;/p&gt;

&lt;p&gt;Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).&lt;/p&gt;

&lt;p&gt;Return intervals after the insertion.&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Thoughts
&lt;/h3&gt;

&lt;p&gt;Brute force: push the new interval, then sort by start time and merge all the remaining intervals. The data is already sorted though… can we use that to make this more efficient?&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Draw a timeline diagram for sure. Doing that is one of the most helpful things when solving these interval problems.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Breaking it down
&lt;/h3&gt;

&lt;p&gt;Lets look at the example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/6a141b5edc4de4ff1c8023a96ad11600/30c92/example1.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5Yd2S4pD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/6a141b5edc4de4ff1c8023a96ad11600/f058b/example1.png" alt="example1" title="example1" width="630" height="686"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From looking at this, we can figure out that the right spot to insert the interval is between the first and second interval in the list.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;So to find the insertion point, we have to find the first interval that overlaps with the new interval&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Lets look at the second example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/da12dbf85200da58b87a3437dffc7d79/307e7/example2.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bLQSc7nt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/da12dbf85200da58b87a3437dffc7d79/f058b/example2.png" alt="example2" title="example2" width="630" height="465"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So we can find our insertion point by iterating through the intervals and checking if the new interval overlaps with the current one we are iterating through.&lt;/p&gt;

&lt;p&gt;Notice how the intervals before the insertion will stay as is. They will not be subject to merge. However, all the intervals after insertion may be subject to merge.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;With this in mind, we could iterate through the intervals while there is no overlap with the new interval, and push intervals into a results array. Then we can iterate through the remaining values, merge if necessary, and push into the results array.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s step through it:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/34905f6a3556a0f479b7a189624dcef8/86a1e/firstLoop.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oBpw1hfW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/34905f6a3556a0f479b7a189624dcef8/f058b/firstLoop.png" alt="firstLoop" title="firstLoop" width="630" height="536"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once the loop breaks we can push the new interval into the results.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/a3e5010aeca2c2e2b560e3ad901b1583/17474/addNewIntToResults.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4Ujcf60q--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/a3e5010aeca2c2e2b560e3ad901b1583/17474/addNewIntToResults.png" alt="addNewIntToResults" title="addNewIntToResults" width="312" height="76"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From here this will resemble a merge interval problem. We can iterate through the remaining intervals, and merge when we have to. If you are not familiar with this problem, I highly recommend that you work on that first.&lt;/p&gt;

&lt;p&gt;Stepping through the second half:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/61ec82b89c28d2a4ad85219372bf5361/5fd3e/secondLoop1.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--54KyLNQA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/61ec82b89c28d2a4ad85219372bf5361/5fd3e/secondLoop1.png" alt="secondLoop1" title="secondLoop1" width="594" height="552"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/b100fcae7f263966318ea97124b3602e/af590/secondLoopPart2.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--skpoibM---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/b100fcae7f263966318ea97124b3602e/af590/secondLoopPart2.png" alt="secondLoopPart2" title="secondLoopPart2" width="626" height="492"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Lastly, return our results:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.deepdevblog.com/static/3591628237a5e165bf79004ea2f1c68a/5819f/returnResults.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cSavy3kE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/3591628237a5e165bf79004ea2f1c68a/f058b/returnResults.png" alt="returnResults" title="returnResults" width="630" height="108"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Nice&lt;/p&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;The algorithm will be broken into three parts:&lt;/p&gt;

&lt;p&gt;Part 1&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Iterate through intervals while current interval does not overlap with new interval&lt;/li&gt;
&lt;li&gt;Push interval into results array&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Part 2&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We have found the insertion point, push new interval into results array&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Part 3&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Iterate through the remaining intervals&lt;/li&gt;
&lt;li&gt;If currentInterval and lastInterval overlap

&lt;ul&gt;
&lt;li&gt;Merge intervals&lt;/li&gt;
&lt;li&gt;Pop from results&lt;/li&gt;
&lt;li&gt;Push merged into results&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;If they do not overlap

&lt;ul&gt;
&lt;li&gt;Push into results&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Increment the currentIdx&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally, return results&lt;/p&gt;

&lt;p&gt;Ok, lets code it up!&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const insert = (intervals, newInterval) =&amp;gt; {

    let results = [];
    let currentIdx = 0;

    // Part 1
    while (intervals[currentIdx] &amp;amp;&amp;amp; intervals[currentIdx][1] &amp;lt; newInterval[0]) {
        results.push(intervals[currentIdx]);
        currentIdx++;
    }

    // Part 2
    results.push(newInterval);

    // Part 3
    while(currentIdx &amp;lt; intervals.length) {
        let lastInterval = results[results.length - 1];
        let currentInterval = intervals[currentIdx];
        if (lastInterval[1] &amp;lt; currentInterval[0]) {
            results.push(currentInterval);
        } else {
            let merged = [
                Math.min(currentInterval[0], lastInterval[0]),
                Math.max(currentInterval[1], lastInterval[1])
            ]
            results.pop();
            results.push(merged);
        }
        currentIdx++;
    }

    return results;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;The time complexity of this algorithm is O(N), where N is the number of intervals in the list. The space complexity is O(N) since we are creating a new list.&lt;/p&gt;

&lt;p&gt;I remember when first attempting this, it was really hard to wrap my head around. The biggest thing that has helped me with interval problems in general is remembering the following:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Non overlapping cases are easier to identify than overlapping cases&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is key from an implementation stand point. It’s must easier to write code to determine if intervals don’t overlap, versus the cases that they do. Good way to see this for your self is to draw some diagrams, and identify all the ways that two intervals can overlap, and all the ways that they won’t. Highly recommend that you explore this.&lt;/p&gt;

&lt;p&gt;Thanks for reading. Hope this was helpful!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 143. Reorder List</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sat, 12 Feb 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-143-reorder-list-2fkm</link>
      <guid>https://dev.to/vickdayaram/leetcode-143-reorder-list-2fkm</guid>
      <description>&lt;p&gt;Solving LeetCode 143. Reorder List. &lt;a href="https://leetcode.com/problems/reorder-list/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;You are given the head of a singly linked-list. The list can be represented as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;L0 → L1 → … → Ln - 1 → Ln
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reorder the list to be on the following form:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You may not modify the values in the list’s nodes. Only nodes themselves may be changed.&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: head = [1,2,3,4]
Output: [1,4,2,3]

Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Thoughts
&lt;/h3&gt;

&lt;p&gt;Hmmm… After some thought, it became clear that I’d have to solve a couple of sub problems. The way I realized this was by looking at the input and output, and walking through some examples by hand. Drawing things out by hand is recommended by mostly everyone, and with great reason. A tool that I have been using lately to do this is &lt;a href="https://excalidraw.com/"&gt;excalidraw&lt;/a&gt;. It’s been super helpful.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;So, Draw things!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Breaking it down
&lt;/h3&gt;

&lt;p&gt;Let’s take an example:&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/0e2e3a64eb04306b6d08f92abec1e9c8/078fe/inputOutput.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8H9r_TRn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/0e2e3a64eb04306b6d08f92abec1e9c8/f058b/inputOutput.png" alt="inputOutput" title="inputOutput" width="630" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It looks like we would like to re order the list in a way where we are interleaving the numbers from the end of the list into the beginning.&lt;/p&gt;

&lt;p&gt;The pattern would be to start with the last node, 5 in this case, and place it between the 1 and the 2. Then take the next last node, 4, and place it between the 2 and the 3.&lt;/p&gt;

&lt;p&gt;We have two sets of numbers. Set A, the set we will insert nodes into, and Set B, the nodes that we will insert into Set A. Since we are only given one list however, we have to determine where one set of number ends and the other begins. From the example above, we can see that the middle of the list is this spot.&lt;/p&gt;

&lt;p&gt;We can find the middle of the list, and then have two lists that we can work with. To find the middle of a linked list we can use the fast and slow pointer approach. With this approach we would end up with something like:&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/d04f933dece2f25848547ba00e4a70af/d9199/twoLists.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--C69sETLi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/d04f933dece2f25848547ba00e4a70af/f058b/twoLists.png" alt="twoLists" title="twoLists" width="630" height="320"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This looks like something we can work with. Although it will be hard to work with the second list since we want to start backward. This is a singly linked list so we don’t have a reference to the previous node.&lt;/p&gt;

&lt;p&gt;What if it was reversed? Then our lists would look something like:&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/34fe6a84f5002566113bfc5738f8a22c/0a867/twoListsSecondReversed.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IY7QGC4r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/34fe6a84f5002566113bfc5738f8a22c/f058b/twoListsSecondReversed.png" alt="twoListsSecondReversed" title="twoListsSecondReversed" width="630" height="318"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Instead of having two separate lists, we could have two lists that end on the same node. Something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/fbeea9fa215fcbb9f50b0965645e0c78/f7a31/twoListsSecondReversedConnected.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Y9NSB-ez--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/fbeea9fa215fcbb9f50b0965645e0c78/f7a31/twoListsSecondReversedConnected.png" alt="twoListsSecondReversedConnected" title="twoListsSecondReversedConnected" width="458" height="249"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Our algorithm implementation will be written expecting to operate on this data structure (two lists that end on a shared node). Keep this in mind. Disconnecting the two lists would work as well, but the implementation would be different.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So we will find the middle of the linked list, and reverse the second half. Once we get here we have to figure out how to interleave the nodes of the two lists. This is the tricky part.&lt;/p&gt;

&lt;p&gt;We can iterate through both the lists, and update the pointers as we go. Let’s look at an overview of the process:&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/abdf69e42b889ba1844567d05bb11bdd/267f6/ourVariables.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--t_iR-8Sz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/abdf69e42b889ba1844567d05bb11bdd/267f6/ourVariables.png" alt="ourVariables" title="ourVariables" width="513" height="265"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;During iteration&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/e6c27d2f8edbdd4b28304c00313fc938/13a9a/firstHalfUpdatePointers.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FDuV0v0m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/e6c27d2f8edbdd4b28304c00313fc938/f058b/firstHalfUpdatePointers.png" alt="firstHalfUpdatePointers" title="firstHalfUpdatePointers" width="630" height="415"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/664532cbda00ab14534bc84f77f7da80/86389/secondHalfUpdatePointers.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--iz1s5E_y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/664532cbda00ab14534bc84f77f7da80/86389/secondHalfUpdatePointers.png" alt="secondHalfUpdatePointers" title="secondHalfUpdatePointers" width="574" height="457"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Looks like things would work. Lets take a look at how our loop would break in this case:&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/06a86bfb6aa5991bbd48bb70ec192b67/6b9fd/lastIterationForOddNumberLinkedList.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5fzyGGfk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/06a86bfb6aa5991bbd48bb70ec192b67/6b9fd/lastIterationForOddNumberLinkedList.png" alt="lastIterationForOddNumberLinkedList" title="lastIterationForOddNumberLinkedList" width="518" height="366"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see, we end up in a situation where&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;firstHalf = 3 -&amp;gt; null
secondHalf = 3 -&amp;gt; null
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Following our algorithm&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let nextFirstHalf = firstHalf.next // null
firstHalf.next = secondHalf // 3, circular reference
firstHalf = nextFirstHalf // null

let nextSecondHalf = secondHalf.next // 3, circular reference
secondHalf.next = firstHalf // break circular reference, now 3 -&amp;gt; null
secondHalf = nextSecondHalf // 3, with no circular reference
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, things would just work once the loop breaks. Nice!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;But… How would the loop break with an even number of nodes?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I’ve added a node to our example, lets pick it up and go through it to find out.&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/fb937574b90e9e0c9e132ac745834b8d/38cea/evenNodesIterationOne.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--g65Sdc-Y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/fb937574b90e9e0c9e132ac745834b8d/f058b/evenNodesIterationOne.png" alt="evenNodesIterationOne" title="evenNodesIterationOne" width="630" height="435"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/ac2368155f138dc19395541e9faef141/38cea/evenNodesIterationTwo.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--77dY22DA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/ac2368155f138dc19395541e9faef141/f058b/evenNodesIterationTwo.png" alt="evenNodesIterationTwo" title="evenNodesIterationTwo" width="630" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/cceb3ec57989ea4ac2305fc7aebf2c58/8ae3e/evenNodesIterationThree.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_R4aUfyc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/cceb3ec57989ea4ac2305fc7aebf2c58/f058b/evenNodesIterationThree.png" alt="evenNodesIterationThree" title="evenNodesIterationThree" width="630" height="382"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this case, secondHalf would be null, and firstHalf.next would be pointing to itself. As you can see we end up with a cycle.&lt;/p&gt;

&lt;p&gt;To ensure we return a proper list without a cycle, we have to check to make sure that firstHalf.next equals null after the loop breaks. If it doesn’t, set it to null to remove the cycle&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The last iteration is key here! This tripped me up for sure!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;Steps we need to solve this problem from our breakdown analysis:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Find middle of list&lt;/li&gt;
&lt;li&gt;Reverse second half&lt;/li&gt;
&lt;li&gt;Use to pointers to iterate through both lists, and interleave the nodes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Finding the middle of the linked list&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use a two pointer approach

&lt;ul&gt;
&lt;li&gt;Previous pointer, Slow pointer, and Fast pointer&lt;/li&gt;
&lt;li&gt;Once Fast reaches the end, Slow will be the middle node of the list&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Reverse the second half of the list&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Write a helper function to reverse the list starting from the slow node&lt;/li&gt;
&lt;li&gt;The function should return the new head of this list, this value will be our secondHalf&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Interleave the nodes&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a pointer for the firstHalf&lt;/li&gt;
&lt;li&gt;Iterate through while firstHalf and secondHalf are not null&lt;/li&gt;
&lt;li&gt;Update pointers for the firstHalf

&lt;ul&gt;
&lt;li&gt;Store the nextFirstHalf&lt;/li&gt;
&lt;li&gt;Set firstHalf.next to secondHalf&lt;/li&gt;
&lt;li&gt;Set firstHalf to nextFirstHalf&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Update pointers for the secondHalf

&lt;ul&gt;
&lt;li&gt;Store the nextSecondHalf&lt;/li&gt;
&lt;li&gt;Set secondHalf.next to firstHalf&lt;/li&gt;
&lt;li&gt;Set secondHalf to nextSecondHalf&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Return head (Since we are just changing pointers, we can return the original head of the list we were given)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Alright, lets code it up!&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const reorderList = (head) =&amp;gt; {

    // Find the middle
    let slow = head;
    let fast = head;

    while (fast &amp;amp;&amp;amp; fast.next) {
        slow = slow.next;
        fast = fast.next.next;
    }

    // reverse second half
    let secondHalf = reverseList(slow);

    // interleave nodes
    let firstHalf = head;

    while (firstHalf &amp;amp;&amp;amp; secondHalf) {
        // Update firstHalf pointers
        let nextFirstHalf = firstHalf.next;
        firstHalf.next = secondHalf;
        firstHalf = nextFirstHalf

        // Update secondHalf pointers
        let nextSecondHalf = secondHalf.next;
        secondHalf.next = firstHalf;
        secondHalf = nextSecondHalf;
    }

    // remove circular dependency if it exists
    if (firstHalf &amp;amp;&amp;amp; firstHalf.next !== null) {
        firstHalf.next = null;
    }
    // return original head since we were just changing pointers
    return head;
}

const reverseList = (node) =&amp;gt; {
    let prev = null;
    while (node) {
        let nextNode = node.next;
        node.next = prev;
        prev = node;
        node = nextNode;
    }
    return prev;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;This was an interesting problem. The solution I am using here is from educative.io. Using two linked lists that point to the same node wasn’t something that came to my mind. This data structure makes the algorithm slightly nicer though.&lt;/p&gt;

&lt;p&gt;Without knowing that solution, disconnecting the lists is a more natural solution. The crux with that approach also reveals it self in the last iteration. You have to add some additional logic in the loop to handle some cases.&lt;/p&gt;

&lt;p&gt;I challenge you to give that a shot. Draw out a diagram and work through it slowly, iteration by iteration.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Sometimes, you have to go slow to go fast!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hope this was helpful!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 581. Shortest Unsorted Continuous Subarray</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sun, 23 Jan 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-581-shortest-unsorted-continuous-subarray-489e</link>
      <guid>https://dev.to/vickdayaram/leetcode-581-shortest-unsorted-continuous-subarray-489e</guid>
      <description>&lt;p&gt;Solving LeetCode 581, Shortest Unsorted Continuous Subarray. &lt;a href="https://leetcode.com/problems/shortest-unsorted-continuous-subarray/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.&lt;/p&gt;

&lt;p&gt;Return the shortest such subarray and output its length.&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Input: nums = [1,2,3,4]
Output: 0

Input: nums = [1]
Output: 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Thoughts
&lt;/h3&gt;

&lt;p&gt;This problem tripped me up. Grasping what you need to do is straight forward, but I had to spend some time coming up with a way to do this. What helped me get un-stuck is looking at examples and looking for a pattern. Doing this helps me understand more deeply what I am trying to find.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Once you know what you need to find, it’s easier to formulate a plan to get to a solution. So ask yourself often, “What I’m I looking for?”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What we are looking for&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The minimum number out of order&lt;/li&gt;
&lt;li&gt;The maximum number out of order&lt;/li&gt;
&lt;li&gt;The index to insert the minimum number for it to be in order&lt;/li&gt;
&lt;li&gt;The index to insert the maximum number for it to be in order&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Break down the problem and make it easy&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="///static/77f9e3342487430058de1b5b70bd401c/32956/camara-pieces.jpg"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o6W9ZeRc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/77f9e3342487430058de1b5b70bd401c/828fb/camara-pieces.jpg" alt="camara pieces" title="camara pieces" width="630" height="421"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;Keeping in mind the problems we need to solve, lets look at our Algorithm Plan.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Iterate from left to right and look for the first number out of order

&lt;ul&gt;
&lt;li&gt;Number out of order will be &lt;code&gt;arr[i] &amp;gt; arr[i + 1]&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;If no number is found, return, array is sorted&lt;/li&gt;
&lt;li&gt;Call this the lowIdx&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Iterate from right to left and look for the first number out of order

&lt;ul&gt;
&lt;li&gt;Number out of order will be &lt;code&gt;arr[i] &amp;lt; arr[i - 1]&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Call this the highIdx&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Look for the minimum number in the subarray from the above indexes&lt;/li&gt;
&lt;li&gt;Look for the maximum number in the subarray from the above indexes&lt;/li&gt;
&lt;li&gt;Expand the subarray if needed

&lt;ul&gt;
&lt;li&gt;Decrement the lowIdx while the current value at low index is greater than the minNumber you found.&lt;/li&gt;
&lt;li&gt;Increment the highIdx while the current value at the high index is less than the maxNumber you found.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Return &lt;code&gt;maxIdx - minIdx + 1&lt;/code&gt;. This is the length of the min subArray the needs to be sorted&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s our plan! As you can tell by looking at it, we are just solving our sub problems, one sub problem at a time.&lt;/p&gt;

&lt;p&gt;Lets code it up!&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const findUnSortedSubArray = (array) =&amp;gt; {

    let low = 0;
    let high = array.length - 1;

    while (low &amp;lt; array.length - 1 &amp;amp;&amp;amp; array[low] &amp;lt;= array[low + 1]) {
        low++;
    }

    // Array is sorted
    if (low === array.length - 1) {
        return 0;
    }

    while(high &amp;gt;= 0 &amp;amp;&amp;amp; array[high] &amp;gt;= array[high - 1]) {
        high--;
    }

    let arrayMin = Infinity;
    let arrayMax = -Infinity;
    for(let i = low; i &amp;lt;= high; i++) {
        arrayMin = Math.min(arrayMin, array[i]);
        arrayMax = Math.max(arrayMax, array[i]);
    }

    while (low &amp;gt; 0 &amp;amp;&amp;amp; array[low - 1] &amp;gt; arrayMin) {
        low--;
    }

    while (high &amp;lt; array.length - 1 &amp;amp;&amp;amp; array[high + 1] &amp;lt; arrayMax) {
        high++;
    }

    return high - low + 1;    
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;This Algorithm runs in O(N) time and O(1) space. Credit to Educative.io for this solution. It’s very elegant, and it’s a great example of breaking down a problem into sub problems.&lt;/p&gt;

&lt;p&gt;The key takeaway from this problem is to break it down and keep it simple. The first part of solving these questions is teasing out that ambiguity.&lt;/p&gt;

&lt;p&gt;Hope that you enjoyed this walk through.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;So, break it on down, and keep it simple&lt;/p&gt;
&lt;/blockquote&gt;

</description>
    </item>
    <item>
      <title>LeetCode 202. Happy Number</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sun, 23 Jan 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-202-happy-number-5bii</link>
      <guid>https://dev.to/vickdayaram/leetcode-202-happy-number-5bii</guid>
      <description>&lt;p&gt;Solving LeetCode 202, Happy Number. &lt;a href="https://leetcode.com/problems/happy-number/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;Write an algorithm to determine if a number n is happy.&lt;/p&gt;

&lt;p&gt;A happy number is a number defined by the following process:&lt;/p&gt;

&lt;p&gt;Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy. Return true if n is a happy number, and false if not.&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Input: n = 2
Output: false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Thoughts
&lt;/h3&gt;

&lt;p&gt;Happy Number. I didn’t realize numbers could feel emotions…&lt;/p&gt;

&lt;p&gt;HA!&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/f6932c65520a0310119cd21cfd433043/1688a/happy-lama.jpg"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--O6yTTDIc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/f6932c65520a0310119cd21cfd433043/828fb/happy-lama.jpg" alt="happy lama" title="happy lama" width="630" height="839"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I thought I would have to keep track of my solutions. If a solution was equal to 1, then it would be a happy number. If I saw it before, then it would be a sad number.&lt;/p&gt;

&lt;p&gt;This solution would require extra space though… can we do better?&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Could we solve with with O(1) space?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Indeed we can by using slow and fast pointers. Lets see how!&lt;/p&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;The key insight here is that we are searching for a cycle. Either a cycle that gets stuck in a number 1, or a cycle that doesn’t. Lets keep that in mind as we go through this Algorithm plan.&lt;/p&gt;

&lt;p&gt;Approach Overview&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Set up two pointers, a slow one and a fast one

&lt;ul&gt;
&lt;li&gt;Slow = number&lt;/li&gt;
&lt;li&gt;Fast = getNextSum(number)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;While fast != 1 &amp;amp;&amp;amp; slow != fast&lt;/li&gt;
&lt;li&gt;Slow pointer will solve the problem for the current number&lt;/li&gt;
&lt;li&gt;Fast pointer will solve the problem for two steps ahead&lt;/li&gt;
&lt;li&gt;When the loops break

&lt;ul&gt;
&lt;li&gt;return fast === 1&lt;/li&gt;
&lt;li&gt;If this is true, the number is happy, else it’s sad&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;getNextSum implementation&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Accepts number&lt;/li&gt;
&lt;li&gt;Declare sum variable and set to zero&lt;/li&gt;
&lt;li&gt;While number &amp;gt; 0

&lt;ul&gt;
&lt;li&gt;Get the leading digit with modulo operator &lt;code&gt;number % 10&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Update the sum with the square value &lt;code&gt;sum = digit * digit&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Remove the leading digit from the number &lt;code&gt;number = Math.floor(number/10)&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Return the sum&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s our plan. Overall this algorithm is fairly easy to implement. Nothing fancy here.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Once you realize that you are searching for cycles, this solution follows nicely. That’s the key insight we need to uncover.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Lets code it up!&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const isHappy = (number) =&amp;gt; {
    let slow = number;
    let fast = getNextSum(number);
    while(fast !== 1 &amp;amp;&amp;amp; slow !== fast) {
        slow = getNextSum(slow);
        fast = getNextSum(getNextSum(fast));
    }
    return fast === 1;
}

const getNextSum = (number) =&amp;gt; {
    let sum = 0;
    while(number &amp;gt; 0) {
        let digit = number % 10;
        sum += digit * digit;
        number = Math.floor(number / 10);
    }
    return sum;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;This Algorithm runs in O(logN) time and O(1) space. The time complexity here is hard to determine. It requires some real insight into the numbers.&lt;/p&gt;

&lt;p&gt;For a detailed time complexity analysis I’d highly recommend the solution section on leetCode &lt;a href="https://leetcode.com/problems/happy-number/solution/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Hope the walk through was helpful!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 844. Backspace String Compare</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sat, 22 Jan 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-844-backspace-string-compare-2db4</link>
      <guid>https://dev.to/vickdayaram/leetcode-844-backspace-string-compare-2db4</guid>
      <description>&lt;p&gt;Solving LeetCode 844, Backspace String Compare. &lt;a href="https://leetcode.com/problems/backspace-string-compare/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;Given two strings s and t, return true if they are equal when both are typed into empty text editors. ’#’ means a backspace character.&lt;/p&gt;

&lt;p&gt;Note that after backspacing an empty text, the text will continue empty.&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".

Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".

Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Thoughts
&lt;/h3&gt;

&lt;p&gt;Ok, I can use a stack, array, or maybe even build a new string with backspaces applied?!!&lt;/p&gt;

&lt;p&gt;But…&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Can you solve it in O(n) time and O(1) space?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hmmm…&lt;/p&gt;

&lt;p&gt;Well… I mean… I guess… Yea… Hmm…&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/7ed3f89de9ddf93c4408061843999991/c83bb/thinking-monkey.jpg"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Si_UFs12--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/7ed3f89de9ddf93c4408061843999991/828fb/thinking-monkey.jpg" alt="thinking monkey" title="thinking monkey" width="630" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Spoiler, Yes we can. Lets take a look and see how&lt;/p&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;How can this work? O(n) and O(1) space…&lt;/p&gt;

&lt;p&gt;We can use a two pointer approach to achieve this&lt;/p&gt;

&lt;p&gt;Overall Execution&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Set up two pointers

&lt;ul&gt;
&lt;li&gt;One for the first string, set to the last character&lt;/li&gt;
&lt;li&gt;One for the second string, set to the last character&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;We will iterate through each character until we reach the first character of each string. Iterate while sIdx &amp;gt;= 0 || tIdx &amp;gt;= 0. This will ensure that we can get to the end of the strings if they are different lengths

&lt;ul&gt;
&lt;li&gt;For each iteration we will look for the next valid character idx&lt;/li&gt;
&lt;li&gt;Valid character idx will be a an idx that will be part of the final string after backspaces are applied.&lt;/li&gt;
&lt;li&gt;We will write a helper function for this functionality since we will need it for both strings.&lt;/li&gt;
&lt;li&gt;Once we have a valid idx for both strings we will compare them.&lt;/li&gt;
&lt;li&gt;If they are the same

&lt;ul&gt;
&lt;li&gt;Decrement the pointers&lt;/li&gt;
&lt;li&gt;Continue to check the next character&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Else, return false and break. Strings are not equivalent&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;If the loop breaks check if sIdx === tIdx.

&lt;ul&gt;
&lt;li&gt;If they do, the strings are equivalent.&lt;/li&gt;
&lt;li&gt;This is a case we will run into if the backspaces wind up creating an empty string for both strings and return -1s.&lt;/li&gt;
&lt;li&gt;If one string becomes empty, and not the other, then they are not equivalent.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Valid Character Helper Function&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Args: currentIdx, string&lt;/li&gt;
&lt;li&gt;Set up a backspace count variable equal to 0&lt;/li&gt;
&lt;li&gt;If the current character is not a ”#”

&lt;ul&gt;
&lt;li&gt;If backspace count is 0&lt;/li&gt;
&lt;li&gt;return currentIdx&lt;/li&gt;
&lt;li&gt;If backspace count is &amp;gt; 0&lt;/li&gt;
&lt;li&gt;decrement backspace count&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;If the current character is a ”#”

&lt;ul&gt;
&lt;li&gt;Increment backspace count&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Decrement currentIdx for each iteration&lt;/li&gt;
&lt;li&gt;Return -1 if there are no more characters&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;The helper function is what’s doing most of the work here. Notice how we are finding the right indexes to compare here in O(1) space.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That’s our plan. Lets code it up!&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const backspaceCompare = (s, t) =&amp;gt; {
    let sIdx = s.length - 1;
    let tIdx = t.length - 1;

    while (sIdx &amp;gt;= 0 || tIdx &amp;gt;= 0) {
        sIdx = getValidIdx(s, sIdx);
        tIdx = getValidIdx(t, tIdx);
        if (s[sIdx] !== t[tIdx]) {
            return false;
        }
        sIdx--;
        tIdx--;
    }

    return sIdx === tIdx;
}

const getValidIdx = (string, idx) =&amp;gt; {
    let backspaceCount = 0;
    while(idx &amp;gt;= 0) {
        let char = string[idx];
        if (char !== "#" &amp;amp;&amp;amp; backspaceCount === 0) {
            return idx;
        }
        if (char !== "#" &amp;amp;&amp;amp; backspaceCount &amp;gt; 0) {
            backspaceCount--;
        }
        if (char === "#") {
            backspaceCount++;
        }
        idx--;
    }
    // At this point we would return -1 if there are no more valid chars
    return idx;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;This Algorithm runs in O(n) time and O(1) space. We completed our challenge! The crux here is figuring out how to apply the backspaces without using extra space. When I took on the challenge that’s the part that I struggled with the most. The pointer approach works quite beautifully.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The aha moment for me was that I don’t need to compare the entire strings in one go, I can do it character by character. That insight really helps open up the door to this approach.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hope you found this walk through helpful!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 75. Sort Colors</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sun, 16 Jan 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-75-sort-colors-28ij</link>
      <guid>https://dev.to/vickdayaram/leetcode-75-sort-colors-28ij</guid>
      <description>&lt;p&gt;Solving LeetCode 75. Sort Colors with a two pointer approach. &lt;a href="https://leetcode.com/problems/sort-colors/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;p&gt;This problem is also known ad the Dutch National Flag problem because the flag has three colors.&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.&lt;/p&gt;

&lt;p&gt;We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.&lt;/p&gt;

&lt;p&gt;You must solve this problem without using the library’s sort function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Input: nums = [2,0,1]
Output: [0,1,2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This problem is simple enough. But can we solve it in O(n) time without any extra space?!&lt;/p&gt;

&lt;p&gt;Take a breath to think about it…&lt;/p&gt;

&lt;p&gt;&lt;a href="///static/acd493f5a542922bec18c7c1bd7a433c/c08c5/yawning-cat.jpg"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--avUH4YjK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.deepdevblog.com/static/acd493f5a542922bec18c7c1bd7a433c/828fb/yawning-cat.jpg" alt="yawning cat" title="yawning cat" width="630" height="419"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;AAAAHHHH… Yes! But how? Two pointer approach to the rescue&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;The intentions of the machine we will create…&lt;/p&gt;

&lt;p&gt;Execution&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create three global variables for positions

&lt;ul&gt;
&lt;li&gt;idx, iterator, current value&lt;/li&gt;
&lt;li&gt;low, last lowest index, for 0s&lt;/li&gt;
&lt;li&gt;high, last highest index, for 2s&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Iterate number by number until we reach the current high value

&lt;ul&gt;
&lt;li&gt;Implement this with a while loop, while idx &amp;lt;= high&lt;/li&gt;
&lt;li&gt;It’s important to use &lt;code&gt;high&lt;/code&gt; here because the value will change. We need the loop to terminate early for things to work as expected.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Run checks

&lt;ul&gt;
&lt;li&gt;If the num === 0&lt;/li&gt;
&lt;li&gt;swap values with left pointer&lt;/li&gt;
&lt;li&gt;increment the left pointer&lt;/li&gt;
&lt;li&gt;increment idx&lt;/li&gt;
&lt;li&gt;If the num === 2&lt;/li&gt;
&lt;li&gt;swap values with the right pointer&lt;/li&gt;
&lt;li&gt;decrement the right pointer&lt;/li&gt;
&lt;li&gt;If the num === 1&lt;/li&gt;
&lt;li&gt;increment the idx, this value is in the right place&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;return the array&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Planning is a crucial part of solving problems. Take the time to plan and set your self up for a easy execution.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Lets code it up!&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const swap = (values, iOne, iTwo) =&amp;gt; {
    const temp = values[iOne];
    values[iOne] = values[iTwo];
    values[iTwo] = temp;
}

const sortColors = (nums) =&amp;gt; {

    let idx = 0;
    let low = 0;
    let high = nums.length - 1;

    while (idx &amp;lt;= high) {
        let val = nums[idx];
        if (val === 0) {
            swap(nums, low, idx);
            low++;
            idx++;
        } else if (val === 2) {
            swap(nums, high, idx);
            high--;
        } else {
            idx++;
        }
    }
    return nums;
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;This algorithm runs in O(n) time with O(1) space. Very nice. Satisfying these constraints is the hardest part of this problem. Using the two pointer approach works quite nicely. I have used two pointers before but using them in this fashion is new to me. This is a great one to visualize in your mind a bit as far as how it’s actually working.&lt;/p&gt;

&lt;p&gt;When writing the plan section I didn’t think about the helper function for the swapping. The helper function dawned on me as I was coding up the solution. I think shaping your algorithm a bit as you go is ok. Figuring out how to structure it while you are coding up though… I’m sure it can be done, but it’s not the best approach.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Take the time to plan. A Wizard in the future will thank you. That Wizard will be you, if you hone in your planning game.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hope you found this walk through helpful!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 16. 3Sum Closest</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sat, 15 Jan 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-16-3sum-closest-4aoe</link>
      <guid>https://dev.to/vickdayaram/leetcode-16-3sum-closest-4aoe</guid>
      <description>&lt;p&gt;Solving LeetCode 16. 3Sum Closest, with a two pointer approach. &lt;a href="https://leetcode.com/problems/3sum-closest/"&gt;Click here&lt;/a&gt; and try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.&lt;/p&gt;

&lt;p&gt;Return the sum of the three integers.&lt;/p&gt;

&lt;p&gt;You may assume that each input would have exactly one solution.&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Input: nums = [0,0,0], target = 1
Output: 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This problem is interesting. What you are asked to is simple, and is easy to understand. Today we will work on building out a solution that runs in O(n^2) by using a two pointer approach.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Algorithm Plan
&lt;/h3&gt;

&lt;p&gt;The intentions of the machine, and how it will run…&lt;/p&gt;

&lt;p&gt;Execution&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sort the array of numbers up front. Two pointer approach only works with a sorted set of numbers.&lt;/li&gt;
&lt;li&gt;Iterate through each value in the array until array.length - 2. This ensures we always have triplets and don’t have to deal with out of bound errors.&lt;/li&gt;
&lt;li&gt;For each iteration

&lt;ul&gt;
&lt;li&gt;Set up a left var equal to i + 1&lt;/li&gt;
&lt;li&gt;Set up a right var equal to array.length - 1&lt;/li&gt;
&lt;li&gt;Set up a while loop, while left &amp;lt; right&lt;/li&gt;
&lt;li&gt;Calculate current sum&lt;/li&gt;
&lt;li&gt;Run checks

&lt;ul&gt;
&lt;li&gt;If we found a better answer, update ClosestSum&lt;/li&gt;
&lt;li&gt;Use Math.abs, remember there could be negative numbers&lt;/li&gt;
&lt;li&gt;If sum is greater than target, decrement right to find a better answer&lt;/li&gt;
&lt;li&gt;If sum is less than target, increment left to find a better answer&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Variables&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ClosestSum: Global Variable to keep track of the best answer. We will return this at the end. Initialize to Infinity&lt;/li&gt;
&lt;li&gt;Left Pointer, Right Pointer, CurrentSum, for each iteration of the loop.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These are the steps that we need to execute for the algorithm.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Special Note on Planning: Planning is an important step when writing code. The better you plan, the easier it will be to code the solution. So take extra time here, its a wise investment. It may seem slower at first, but it’s how you will become a wizard.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Lets code it up!&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const threeSumClosest = (nums, target) =&amp;gt; {

    // Sort the array for two pointer approach
    nums.sort((a, b) =&amp;gt; a - b);

    let closestSum = Infinity;

    for(let i = 0; i &amp;lt; nums.length - 2; i++) {

        let val = nums[i];
        let left = i + 1;
        let right = nums.length - 1;

        while (left &amp;lt; right) {
            const currentSum = val + nums[left] + nums[right];
            const currentDiff = Math.abs(target - currentSum);
            const closestDiff = Math.abs(target - closestSum);

            if (currentDiff &amp;lt; closestDiff) {
                closestSum = currentSum;
            }

            if (target &amp;lt; currentSum) {
                right--;
            } else {
                left++;
            }
        }
    }

    return closestSum;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;This Algorithm runs in O(n^2) time. O(n * log(n)) for the sort plus O(n^2) for the iteration, O(n * log(n) + n^2), which is asymptotically equivalent to O(n^2). Space complexity will be O(n) which is required for sorting.&lt;/p&gt;

&lt;p&gt;The two pointer approach pattern we used here can be used for a variety of other problems similar to this one. It’s a great one to have in your tool belt.&lt;/p&gt;

&lt;p&gt;Hope you found this walk through helpful. If you take one thing away from this I hope it’s the planning piece. Take the time to plan. It’s a habit that will help you as an engineer, and life in general.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode 424. Longest Repeating Character Replacement</title>
      <dc:creator>vickdayaram</dc:creator>
      <pubDate>Sat, 08 Jan 2022 00:00:00 +0000</pubDate>
      <link>https://dev.to/vickdayaram/leetcode-424-longest-repeating-character-replacement-1p23</link>
      <guid>https://dev.to/vickdayaram/leetcode-424-longest-repeating-character-replacement-1p23</guid>
      <description>&lt;p&gt;Solving LeetCode 424. Longest Repeating Character Replacement, with a Sliding Window approach. &lt;a href="https://leetcode.com/problems/longest-repeating-character-replacement/"&gt;Click here&lt;/a&gt; to try it out your self!&lt;/p&gt;

&lt;h3&gt;
  
  
  LeetCode Problem Statement
&lt;/h3&gt;

&lt;p&gt;You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.&lt;/p&gt;

&lt;p&gt;Return the length of the longest substring containing the same letter you can get after performing the above operations&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two 'A's with two 'B's or vice versa.

Input: s = "AABABBA", k = 1
Output: 4
Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This was a tough problem for me to wrap my head around. The key for me was getting a better insight into what I was looking for…&lt;/p&gt;

&lt;h3&gt;
  
  
  Working backwards, what does our solution look like?
&lt;/h3&gt;

&lt;p&gt;We are looking for the longest substring that contains the same characters after substituting up to K times.&lt;/p&gt;

&lt;p&gt;In other words we are looking for a substring that contains the max alike letters plus K substitutions. So in any given window our answer should work out to be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const solution = maxLetterCountInWindow + k
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Where solution must be less than the length of the string.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: s = "ABAB", k = 2
Output: 4

window = {A: 2, B: 2} from index 0 to 3;
maxLetterCount = 2;
k = 2;

solution = maxLetterCount + k
solution = 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we can either have a window where the maxLetter is A, or B. In either case we can delete the other letter up to K times, which in this case is 2.&lt;/p&gt;

&lt;p&gt;Example 2:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: s = "AABABBA", k = 1
Output: 4

Solution 1
window = {A: 3, B: 1} from index 0 to 3
maxLetterCount = 3
k = 1

solution = maxLetterCount + k
solution = 4

Solution 2
window = {A: 1, B: 3} fro index 2 to 5
maxLetterCount = 3
k = 1

solution = maxLetterCount + k
solution = 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Understanding this insight turned this hard problem into a manageable one. Let’s look at the code and see how we can apply this.&lt;/p&gt;

&lt;h3&gt;
  
  
  Code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const findLengthOfLongestSubStringWithMaxDeletes = (str, k) =&amp;gt; {

    let maxLength = -Infinity;
    let maxLetterCount = 0; 
    let frequencyMap = {}; // for the given window
    let windowStart = 0;

    for(let windowEnd = 0; windowEnd &amp;lt; s.length; windowEnd++) {
        let rightChar = s[windowEnd];
        if (!frequencyMap[rightChar]) {
            frequencyMap[rightChar] = 0;
        }

        // Keep track of the char frequency in the currentWindow
        frequencyMap[rightChar] += 1;

        // Update the maxLetterCount for the window
        maxLetterCount = Math.max(maxLetterCount, frequencyMap[rightChar]); 

        // Validate the current window to make sure we satisfy the constraints 
        // If the currentLength - maxLetterCount &amp;gt; k 
        // shrink the window since we don't have substitutions left. 
        const currentLength = windowEnd - windowStart + 1;
        if ((currentLength - maxLetterCount) &amp;gt; k) {
            let leftChar = s[windowStart];
            // Remember to decrement the frequencyMap with the character 
            // that is going out of the window
            frequencyMap[leftChar] -= 1;
            windowStart++;
        }

        // Now we have a valid window, so check if we have 
        // found a better answer
        const validLength = windowEnd - windowStart + 1;
        maxLength = Math.max(validLength, maxLength);
    }

    return maxLength;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Summary
&lt;/h3&gt;

&lt;p&gt;This algorithm runs in O(n) time and O(1) space. Given that we only have 26 letters in the english language, that’s a fixed space we would keep in the hashmap which is equivalent to O(1).&lt;/p&gt;

&lt;p&gt;I struggled when solving this problem. Understanding that the length of the substring would equal the maxNumberOfCharacters + k, was the key insight I needed to make a break through.&lt;/p&gt;

&lt;p&gt;Hope you found this helpful!&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
