Explain Dynamic Programming and Other Techniques with Examples
Tags: javascript, programming, tutorial, algorithms
Published: 2023-06-11 11:16:21

<!-- wp:rank-math/toc-block {"headings":[{"key":"9cb1f2c4-cbe5-4aab-9705-8197da83108c","content":"1. Introduction","level":2,"link":"#1-introduction","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"7373c90f-1aea-4cfb-9c08-29a3faa75bf4","content":"2. Longest Increasing Subsequence","level":2,"link":"#2-longest-increasing-subsequence","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"d2efa4eb-31b5-40b8-9bd1-3804134709fc","content":"2.1 Problem Description","level":3,"link":"#2-1-problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"f04777ea-49b2-4996-b462-6d72ad932d5b","content":"2.2 Solution in JavaScript","level":3,"link":"#2-2-solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"6dd4e6b5-208d-4622-a730-ab34547c73ae","content":"3. Longest Common Subsequence ","level":2,"link":"#3-longest-common-subsequence","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"ea0a1b2e-8382-481b-82c5-4b9e222ad8d4","content":"3.1 Problem Description","level":3,"link":"#3-1-problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"22fa9d6c-7f22-4fe7-b07f-326c22157bdf","content":"3.2 Solution in JavaScript","level":3,"link":"#3-2-solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"aa3a7db0-c788-4d2d-815d-8d359f09e447","content":"4. Longest Palindromic Substring","level":2,"link":"#4-longest-palindromic-substring","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"02d7926a-1e05-452b-a12f-c2123b3d5c7a","content":"4.1 Problem Description","level":3,"link":"#4-1-problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"b08a5308-1e87-4b4c-b790-e751dfbb05c6","content":"4.2 Solution in JavaScript","level":3,"link":"#4-2-solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"2b88bef2-7a52-4aed-b207-d9f65c103d06","content":"5. Longest Palindromic Subsequence ","level":2,"link":"#5-longest-palindromic-subsequence","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"1ffc352b-d9ee-4696-a926-e8fc669d0db9","content":"5.1 Problem Description","level":3,"link":"#5-1-problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"78080047-cfb7-4ac2-8646-121b0a1a95bc","content":"5.2 Solution in JavaScript","level":3,"link":"#5-2-solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"b13f54ce-4c31-4748-ac7f-2ea81eac2d4c","content":"6. Maximum Product Subarray ","level":2,"link":"#6-maximum-product-subarray","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"69ab9f86-dfd1-4c92-b8e0-eb5a0147a9e1","content":"6.1 Problem Description","level":3,"link":"#6-1-problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"92608531-c492-46c0-a6c2-fa5ae68b24d9","content":"6.2 Solution in JavaScript ","level":3,"link":"#6-2-solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"f2b470ec-4ea0-4fb3-b1e9-a4a5cd53a9e0","content":"7. Largest Rectangle in a Histogram ","level":2,"link":"#7-largest-rectangle-in-a-histogram","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"f7b21942-a8d8-48f3-8ce3-fe943b96f7ab","content":"7.1 Problem Description","level":3,"link":"#7-1-problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"3ff5c498-9690-4c05-8ad0-9995141e4cdd","content":"7.2 Solution in JavaScript","level":3,"link":"#7-2-solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"304916bf-0c69-4504-a42c-16f39f7c806d","content":"8. Egg Dropping Problem","level":2,"link":"#8-egg-dropping-problem","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"0e91e81b-e2f6-4711-89a4-fa8014fe4f7f","content":"8.1 Problem Description","level":3,"link":"#8-1-problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"07c527ee-7a84-4f0e-b9cd-db2bf57c8e6a","content":"8.2 Solution in JavaScript","level":3,"link":"#8-2-solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"c565261c-94a0-4d13-ad22-a2554500dc25","content":"9. Counting Bits","level":2,"link":"#9-counting-bits","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"bf431a5a-a276-43b9-a427-b830d72d25fb","content":"9.1 Problem Description","level":3,"link":"#9-1-problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"6df7edbf-8413-4c9e-9489-d4aa37546178","content":"9.2 Solution in JavaScript","level":3,"link":"#9-2-solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"ec9a79b6-2555-4e01-9d43-0ab01943fa12","content":"10. Perfect Squares","level":2,"link":"#10-perfect-squares","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"812a92ea-ea37-4a76-bb1b-3edaef401a00","content":"10.1 Problem Description","level":3,"link":"#10-1-problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"e753dfcd-bcbe-4bdb-89bb-eaf7ab6f5192","content":"10.2 Solution in JavaScript","level":3,"link":"#10-2-solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"e2337821-8f67-4633-b574-a4cce68925ab","content":"11. Unique Paths","level":2,"link":"#11-unique-paths","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"ad189094-1cc9-41f9-8917-92bda728cc64","content":"Problem Description","level":3,"link":"#problem-description","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"a54b7d82-5110-48a5-92c8-709b340a046c","content":"Solution in JavaScript","level":3,"link":"#solution-in-java-script","disable":false,"isUpdated":false,"isGeneratedLink":true},{"key":"6c24c51c-12ec-455e-9437-a83a5781a2e9","content":"Conclusion","level":2,"link":"#conclusion","disable":false,"isUpdated":false,"isGeneratedLink":true}],"listStyle":"ul"} -->
<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><nav><ul><li class=""><a href="#1-introduction">1. Introduction</a></li><li class=""><a href="#2-longest-increasing-subsequence">2. Longest Increasing Subsequence</a><ul><li class=""><a href="#2-1-problem-description">2.1 Problem Description</a></li><li class=""><a href="#2-2-solution-in-java-script">2.2 Solution in JavaScript</a></li></ul></li><li class=""><a href="#3-longest-common-subsequence">3. Longest Common Subsequence </a><ul><li class=""><a href="#3-1-problem-description">3.1 Problem Description</a></li><li class=""><a href="#3-2-solution-in-java-script">3.2 Solution in JavaScript</a></li></ul></li><li class=""><a href="#4-longest-palindromic-substring">4. Longest Palindromic Substring</a><ul><li class=""><a href="#4-1-problem-description">4.1 Problem Description</a></li><li class=""><a href="#4-2-solution-in-java-script">4.2 Solution in JavaScript</a></li></ul></li><li class=""><a href="#5-longest-palindromic-subsequence">5. Longest Palindromic Subsequence </a><ul><li class=""><a href="#5-1-problem-description">5.1 Problem Description</a></li><li class=""><a href="#5-2-solution-in-java-script">5.2 Solution in JavaScript</a></li></ul></li><li class=""><a href="#6-maximum-product-subarray">6. Maximum Product Subarray </a><ul><li class=""><a href="#6-1-problem-description">6.1 Problem Description</a></li><li class=""><a href="#6-2-solution-in-java-script">6.2 Solution in JavaScript </a></li></ul></li><li class=""><a href="#7-largest-rectangle-in-a-histogram">7. Largest Rectangle in a Histogram </a><ul><li class=""><a href="#7-1-problem-description">7.1 Problem Description</a></li><li class=""><a href="#7-2-solution-in-java-script">7.2 Solution in JavaScript</a></li></ul></li><li class=""><a href="#8-egg-dropping-problem">8. Egg Dropping Problem</a><ul><li class=""><a href="#8-1-problem-description">8.1 Problem Description</a></li><li class=""><a href="#8-2-solution-in-java-script">8.2 Solution in JavaScript</a></li></ul></li><li class=""><a href="#9-counting-bits">9. Counting Bits</a><ul><li class=""><a href="#9-1-problem-description">9.1 Problem Description</a></li><li class=""><a href="#9-2-solution-in-java-script">9.2 Solution in JavaScript</a></li></ul></li><li class=""><a href="#10-perfect-squares">10. Perfect Squares</a><ul><li class=""><a href="#10-1-problem-description">10.1 Problem Description</a></li><li class=""><a href="#10-2-solution-in-java-script">10.2 Solution in JavaScript</a></li></ul></li><li class=""><a href="#11-unique-paths">11. Unique Paths</a><ul><li class=""><a href="#problem-description">Problem Description</a></li><li class=""><a href="#solution-in-java-script">Solution in JavaScript</a></li></ul></li><li class=""><a href="#conclusion">Conclusion</a></li></ul></nav></div>
<!-- /wp:rank-math/toc-block -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="1-introduction">1. Introduction</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this article, we will dive into the world of dynamic programming, focusing on solving some programming challenges using also some other techniques. We will break down each problem, present different solutions in JavaScript, and provide a clear, concise explanation.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="2-longest-increasing-subsequence">2. Longest Increasing Subsequence</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="2-1-problem-description">2.1 Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The Longest Increasing Subsequence (LIS) problem is a classic programming challenge that requires finding the length of the longest subsequence of a given sequence, such that all elements of the subsequence are sorted in increasing order. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, consider the sequence [10, 9, 2, 5, 3, 7, 101, 18]. The longest increasing subsequence here is [2, 3, 7, 101], and its length is 4.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="2-2-solution-in-java-script">2.2 Solution in JavaScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To solve the LIS problem in JavaScript, we can use dynamic <a href="https://nerdleveltech.com/how-to-solve-an-algorithm-problem-with-examples/" target="_blank" rel="noreferrer noopener nofollow">programming</a> to break down the problem into smaller subproblems and solve them efficiently. Here's a step-by-step solution with detailed comments to help you understand the code:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function longestIncreasingSubsequence(nums) {
  const n = nums.length;
  if (n === 0) return 0;
  
  // Initialize an array of length n, filled with 1s, as the minimum length of any LIS is 1
  const dp = Array(n).fill(1);
  
  // Iterate through the elements in the nums array
  for (let i = 1; i &lt; n; i++) {
    for (let j = 0; j &lt; i; j++) {
      // Check if the current element is greater than the previous one
      if (nums[i] > nums[j]) {
        // If it is, update the dp array with the maximum length found so far
        dp[i] = Math.max(dp[i], dp[j] + 1);
      }
    }
  }
  
  // Find the maximum length of the LIS by iterating through the dp array
  let maxLIS = dp[0];
  for (let i = 1; i &lt; n; i++) {
    maxLIS = Math.max(maxLIS, dp[i]);
  }
  
  // Return the maximum length of the LIS
  return maxLIS;
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>To understand this solution, let's break down the key parts:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>We initialize an array called <code>dp</code> with the same length as the input array <code>nums</code>, and fill it with 1s. This array will store the length of the LIS ending at each index.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>We then use two nested loops to iterate through the elements in the <code>nums</code> array.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>If the current element is greater than the previous one, we update the <code>dp</code> array with the maximum length found so far.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Finally, we find the maximum length of the LIS by iterating through the <code>dp</code> array and return it.</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p><strong>Time complexity and space complexity are as follows:</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Time Complexity: O(n^2)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The time complexity of the solution is O(n^2) because we have two nested loops. The outer loop iterates over the elements in the input array <code>nums</code> and the inner loop iterates over the elements up to the current index in the outer loop. In the worst case, both loops will run n times, resulting in a total of n * n operations. Therefore, the time complexity is O(n^2).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Space Complexity: O(n)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The space complexity of the solution is O(n) because we are using an additional array <code>dp</code> to store the length of the LIS ending at each index. The size of the <code>dp</code> array is equal to the length of the input array <code>nums</code>, which is n. Apart from the <code>dp</code> array, we use a few variables, but their space consumption is constant and does not depend on the input size. Therefore, the space complexity is O(n).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you ask is there a better and more efficient solution for the same challenge?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Yes, there is a better time complexity solution to the Longest Increasing Subsequence problem using a binary search algorithm. The time complexity for this approach is O(n*log(n)).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here is the code and explanation for the better approach:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function longest_increasing_subsequence(nums) {
    let tails = [];
    tails[0] = nums[0];
    let length = 1;

    for (let i = 1; i &lt; nums.length; i++) {
        if (nums[i] &lt; tails[0]) {
            tails[0] = nums[i];
        } else if (nums[i] > tails[length - 1]) {
            tails[length++] = nums[i];
        } else {
            tails[lower_bound(tails, 0, length - 1, nums[i])] = nums[i];
        }
    }

    return length;
}

function lower_bound(arr, start, end, key) {
    while (start &lt; end) {
        let mid = Math.floor((start + end) / 2);
        if (arr[mid] &lt; key) {
            start = mid + 1;
        } else {
            end = mid;
        }
    }

    return start;
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>In this approach, we maintain an array <code>tails</code>, which stores the minimum tail elements of all increasing subsequences we have seen so far. The <code>tails</code> array is sorted, and its length represents the length of the longest increasing subsequence. We iterate through the input array <code>nums</code> and, for each element:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><!-- wp:list-item -->
<li>If the element is smaller than the first element in <code>tails</code>, we replace the first element with the current element.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>If the element is greater than the last element in <code>tails</code>, we append the element to the end of <code>tails</code>, increasing the length of the LIS by 1.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Otherwise, we find the smallest element in <code>tails</code> that is greater than or equal to the current element using the <code>lower_bound</code> function (binary search), and replace that element with the current element.</li>
<!-- /wp:list-item --></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>This approach is faster because, for each element in the input array, we perform a binary search operation that takes O(log(n)) time. Since there are n elements in the input array, the overall time complexity is O(n*log(n)).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The primary difference between the O(n^2) and O(n<em>log(n)) solutions is the technique used to update the subproblem solutions. The O(n^2) approach uses dynamic programming with a nested loop, whereas the O(n</em>log(n)) approach uses binary search to optimize the updates. The O(n*log(n)) solution is more efficient, especially for large input arrays.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="3-longest-common-subsequence">3. Longest Common Subsequence </h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="3-1-problem-description">3.1 Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The Longest Common Subsequence (LCS) problem is a classic computer science problem that involves finding the longest subsequence common to two given sequences. A subsequence is a sequence that appears in the same order in both sequences but not necessarily consecutively. For example, the longest common subsequence of the strings "ABCD" and "ACDF" is "ACD".</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="3-2-solution-in-java-script">3.2 Solution in JavaScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To solve the Longest Common Subsequence problem, we will use dynamic programming. This approach allows us to break the problem down into smaller subproblems and solve them only once. Here's the JavaScript solution:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function longestCommonSubsequence(str1, str2) {
  const m = str1.length;
  const n = str2.length;
  const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));

  for (let i = 1; i &lt;= m; i++) {
    for (let j = 1; j &lt;= n; j++) {
      if (str1[i - 1] === str2[j - 1]) {
        dp[i][j] = 1 + dp[i - 1][j - 1];
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
      }
    }
  }

  return dp[m][n];
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>To understand the code, let's break it down step by step:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><!-- wp:list-item -->
<li>We first define the lengths of both input strings <code>m</code> and <code>n</code>.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>We create a 2D array <code>dp</code> with dimensions <code>(m + 1) x (n + 1)</code> and initialize all elements to 0.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>We loop through each character of both strings, comparing them at each step.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>If the characters match, we increment the value in the <code>dp</code> array at the current position by adding 1 to the value at the diagonal position (up and left). This represents adding the current matched character to the LCS found so far.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>If the characters don't match, we take the maximum value from either the cell above or the cell to the left. This represents considering the LCS found so far without the current characters.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>After looping through both strings, the value in the bottom-right corner of the <code>dp</code> array represents the length of the Longest Common Subsequence.</li>
<!-- /wp:list-item --></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>The time complexity of this solution is O(m * n), where m and n are the lengths of the input strings. This is because we need to loop through each character in both strings and compare them.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The space complexity of the solution is also O(m * n) due to the 2D array <code>dp</code> that we create to store the intermediate results of the subproblems.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's have some optimization and do a code review. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The dynamic programming solution provided above has a time complexity of O(m * n), where m and n are the lengths of the input strings. While it may not be possible to significantly improve the time complexity for the general case, we can optimize the space complexity of the solution.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The current space complexity is also O(m * n) due to the 2D array <code>dp</code>. We can optimize this by using a rolling array and only keeping track of the current and previous rows. This reduces the space complexity to O(min(m, n)). Here's the optimized JavaScript solution:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function longestCommonSubsequence(str1, str2) {
  if (str1.length &lt; str2.length) {
    [str1, str2] = [str2, str1];
  }

  const m = str1.length;
  const n = str2.length;
  const dp = Array.from({ length: 2 }, () => Array(n + 1).fill(0));

  for (let i = 1; i &lt;= m; i++) {
    for (let j = 1; j &lt;= n; j++) {
      if (str1[i - 1] === str2[j - 1]) {
        dp[i % 2][j] = 1 + dp[(i - 1) % 2][j - 1];
      } else {
        dp[i % 2][j] = Math.max(dp[(i - 1) % 2][j], dp[i % 2][j - 1]);
      }
    }
  }

  return dp[m % 2][n];
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>In this optimized solution, we first swap <code>str1</code> and <code>str2</code> if <code>str1</code> has a shorter length than <code>str2</code>. This ensures that <code>str2</code> is always the shorter string, which reduces space complexity. Then, instead of initializing a 2D array with dimensions <code>(m + 1) x (n + 1)</code>, we create a 2D array with dimensions <code>2 x (n + 1)</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Inside the loops, we update the <code>dp</code> array using the modulo operator (<code>%</code>) to alternate between the two rows. This means that we only store the current row and the previous row, effectively reducing the space complexity to O(min(m, n)).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Please note that the time complexity remains O(m * n) because we still need to loop through each character in both strings and compare them. However, the space complexity is now optimized, making the solution more efficient in terms of memory usage.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="4-longest-palindromic-substring">4. Longest Palindromic Substring</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="4-1-problem-description">4.1 Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The Longest Palindromic Substring problem involves finding the longest contiguous substring of a given string that reads the same forward and backward. For example, given the string "babad", the longest palindromic substring is either "bab" or "aba".</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="4-2-solution-in-java-script">4.2 Solution in JavaScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>One way to solve this problem is by using dynamic programming. Here's the JavaScript solution:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function longestPalindromicSubstring(s) {
  const n = s.length;
  const dp = Array.from({ length: n }, () => Array(n).fill(false));
  let maxLen = 1;
  let start = 0;

  for (let i = 0; i &lt; n; i++) {
    dp[i][i] = true;
  }

  for (let len = 2; len &lt;= n; len++) {
    for (let i = 0; i &lt;= n - len; i++) {
      const j = i + len - 1;

      if (len === 2) {
        dp[i][j] = s[i] === s[j];
      } else {
        dp[i][j] = s[i] === s[j] &amp;&amp; dp[i + 1][j - 1];
      }

      if (dp[i][j] &amp;&amp; len > maxLen) {
        maxLen = len;
        start = i;
      }
    }
  }

  return s.substring(start, start + maxLen);
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>In this solution, we first create a 2D array <code>dp</code>, where <code>dp[i][j]</code> is true if the substring from index <code>i</code> to <code>j</code> is a palindrome. We initialize the diagonal elements of <code>dp</code> as true since single characters are always palindromes.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next, we loop through the string using two nested loops. The outer loop iterates through the possible lengths of substrings (from 2 to the length of the input string), and the inner loop iterates through the starting positions of the substrings. If the current substring is a palindrome, we update the <code>dp</code> array and track the start position and maximum length of the palindrome.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Finally, we return the longest palindromic substring using the <code>substring</code> method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Time complexity: O(n^2), where n is the length of the input string. This is because we need to loop through all possible substrings and check if they are palindromes.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Space complexity: O(n^2), due to the 2D array <code>dp</code> that stores the palindrome information for all possible substrings.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Dynamic programming is just one of the approaches to solve the Longest Palindromic Substring problem, and I provided it because it's a widely-used technique for such problems. However, there are other approaches to solve this problem, and I can provide an alternative solution using an expand-around-center technique.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The expand-around-center technique is based on the idea of iterating through the string and, for each character, expanding outwards to find the longest palindromic substring that includes that character. Here's the solution in JavaScript using this approach:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function expandAroundCenter(s, left, right) {
  while (left >= 0 &amp;&amp; right &lt; s.length &amp;&amp; s[left] === s[right]) {
    left--;
    right++;
  }
  return right - left - 1;
}

function longestPalindromicSubstring(s) {
  if (s == null || s.length &lt; 1) return '';

  let start = 0;
  let end = 0;

  for (let i = 0; i &lt; s.length; i++) {
    const len1 = expandAroundCenter(s, i, i);
    const len2 = expandAroundCenter(s, i, i + 1);
    const len = Math.max(len1, len2);

    if (len > end - start) {
      start = i - Math.floor((len - 1) / 2);
      end = i + Math.floor(len / 2);
    }
  }

  return s.substring(start, end + 1);
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>In this solution, we first define a helper function <code>expandAroundCenter</code>, which returns the length of the longest palindromic substring centered around the given indices. Then, we iterate through the input string and call the helper function to find the longest palindromic substring for each character.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Time complexity: O(n^2), where n is the length of the input string. In the worst case, we need to expand around each character in the input string, which takes quadratic time.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Space complexity: O(1), as we are not using any additional data structures to store intermediate results, and the memory usage does not depend on the size of the input string.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This approach may have better performance than dynamic programming for some cases because it can skip some unnecessary checks when expanding around the center. However, both methods still have a time complexity of O(n^2).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So, is there a better time complexity then O(n^2)?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Yes, there is an algorithm called Manacher's Algorithm that solves the Longest Palindromic Substring problem with a better time complexity of O(n). This algorithm is specifically designed to find the longest palindromic substring more efficiently by avoiding redundant checks and utilizing previously calculated information.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's the implementation of Manacher's Algorithm in JavaScript:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function manachersAlgorithm(s) {
  if (s == null || s.length === 0) return '';

  let modifiedString = '#';
  for (let i = 0; i &lt; s.length; i++) {
    modifiedString += s[i] + '#';
  }

  const p = new Array(modifiedString.length).fill(0);
  let center = 0;
  let rightBoundary = 0;
  let maxLen = 0;
  let maxLenCenter = 0;

  for (let i = 1; i &lt; modifiedString.length - 1; i++) {
    if (rightBoundary > i) {
      const mirror = 2 * center - i;
      p[i] = Math.min(rightBoundary - i, p[mirror]);
    }

    while (
      i + p[i] + 1 &lt; modifiedString.length &amp;&amp;
      i - p[i] - 1 >= 0 &amp;&amp;
      modifiedString[i + p[i] + 1] === modifiedString[i - p[i] - 1]
    ) {
      p[i]++;
    }

    if (i + p[i] > rightBoundary) {
      center = i;
      rightBoundary = i + p[i];
    }

    if (p[i] > maxLen) {
      maxLen = p[i];
      maxLenCenter = i;
    }
  }

  const start = Math.floor((maxLenCenter - maxLen) / 2);
  return s.substring(start, start + maxLen);
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>In this algorithm, we first modify the input string by adding special characters (e.g., '#') between the original characters. This helps to handle even- and odd-length palindromes uniformly. Then, we use an array <code>p</code> to store the palindrome radius centered at each character of the modified string.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We iterate through the modified string and update the palindrome radius for each character while keeping track of the right boundary of the current palindrome and its center. We utilize the information about the previously calculated palindrome radius to skip some redundant checks and avoid extra work.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Time complexity: O(n), where n is the length of the input string. Manacher's Algorithm performs a linear number of operations by avoiding redundant checks and utilizing previously calculated information.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Space complexity: O(n), as we store the palindrome radius for each character of the modified string, which has a length proportional to the input string length.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Manacher's Algorithm provides a faster solution to the Longest Palindromic Substring problem compared to the dynamic programming and expand-around-center methods, which have a time complexity of O(n^2).</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="5-longest-palindromic-subsequence">5. Longest Palindromic Subsequence </h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="5-1-problem-description">5.1 Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this problem, we need to find the longest palindromic subsequence in a given string. Unlike the substring, a subsequence doesn't require the characters to be contiguous in the original string, but they must maintain their order.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="5-2-solution-in-java-script">5.2 Solution in JavaScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We can solve this problem using dynamic programming. The idea is to create a 2D table to store the lengths of the longest palindromic subsequences of the substrings.</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function longestPalindromicSubsequence(s) {
  const n = s.length;
  const dp = Array.from({ length: n }, () => Array(n).fill(0));

  for (let i = 0; i &lt; n; i++) {
    dp[i][i] = 1;
  }

  for (let len = 2; len &lt;= n; len++) {
    for (let i = 0; i &lt;= n - len; i++) {
      const j = i + len - 1;

      if (s[i] === s[j]) {
        dp[i][j] = dp[i + 1][j - 1] + 2;
      } else {
        dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
      }
    }
  }

  return dp[0][n - 1];
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>In this solution, we first initialize a 2D table <code>dp</code> of size <code>n x n</code>, where <code>n</code> is the length of the input string. We set the diagonal elements of <code>dp</code> to 1 since a single character is always a palindrome.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We then iterate through the table, filling it with the lengths of the longest palindromic subsequences for all substrings. If the characters at the beginning and end of the substring are the same, we add 2 to the value of the inner substring. Otherwise, we set the value to the maximum of the previous row and previous column.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The final answer is stored in the top-right cell of the table, <code>dp[0][n - 1]</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Time complexity: O(n^2), where n is the length of the input string. We need to fill the 2D table of size <code>n x n</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Space complexity: O(n^2), as we store the lengths of the longest palindromic subsequences in the <code>dp</code> table.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Our usual question: Is there a better time or space complexity than O(n^2)?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There isn't a significantly better time complexity than O(n^2) for the Longest Palindromic Subsequence problem using dynamic programming. However, you can optimize the space complexity using a rolling array or two 1D arrays instead of a 2D array.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's an optimized solution with a space complexity of O(n):</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function longestPalindromicSubsequence(s) {
  const n = s.length;
  let prev = Array(n).fill(0);
  let curr = Array(n).fill(0);

  for (let i = n - 1; i >= 0; i--) {
    curr[i] = 1;
    for (let j = i + 1; j &lt; n; j++) {
      if (s[i] === s[j]) {
        curr[j] = prev[j - 1] + 2;
      } else {
        curr[j] = Math.max(prev[j], curr[j - 1]);
      }
    }
    [prev, curr] = [curr, prev];
  }

  return prev[n - 1];
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>In this solution, we use two 1D arrays, <code>prev</code> and <code>curr</code>, to represent the previous row and current row of the 2D <code>dp</code> table. This reduces the space complexity to O(n) while maintaining the same time complexity of O(n^2).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In summary, the time complexity remains O(n^2), but the space complexity is improved to O(n) using this optimized approach.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="6-maximum-product-subarray">6. Maximum Product Subarray </h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="6-1-problem-description">6.1 Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The Maximum Product Subarray problem involves finding the contiguous subarray within a one-dimensional array of numbers that has the largest product. The input array may contain both positive and negative numbers.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="6-2-solution-in-java-script">6.2 Solution in JavaScript </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To solve this problem, we can use dynamic programming. We keep track of the maximum and minimum product subarrays ending at each position, as the current number may be negative, which can turn the minimum product into the maximum product when multiplied.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's the solution in JavaScript:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function maxProductSubarray(nums) {
  const n = nums.length;
  let maxProd = nums[0];
  let minProd = nums[0];
  let maxSoFar = nums[0];

  for (let i = 1; i &lt; n; i++) {
    let temp = maxProd;
    maxProd = Math.max(nums[i], Math.max(nums[i] * maxProd, nums[i] * minProd));
    minProd = Math.min(nums[i], Math.min(nums[i] * temp, nums[i] * minProd));
    maxSoFar = Math.max(maxSoFar, maxProd);
  }

  return maxSoFar;
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>In this solution, we iterate through the input array <code>nums</code>. At each position, we calculate the maximum and minimum product subarrays ending at that position. We update the overall maximum product <code>maxSoFar</code> whenever we find a larger product.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The time complexity of this solution is O(n) since we only make one pass through the input array. The space complexity is O(1) as we only use constant extra space to store the intermediate results.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In summary, this JavaScript solution has a time complexity of O(n) and space complexity of O(1) for the Maximum Product Subarray problem.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="7-largest-rectangle-in-a-histogram">7. Largest Rectangle in a Histogram </h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="7-1-problem-description">7.1 Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The Largest Rectangle in a Histogram problem involves finding the largest rectangular area that can be formed within a histogram. A histogram is represented as an array of integers, where each element represents the height of a bar, and the width of each bar is 1.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="7-2-solution-in-java-script">7.2 Solution in JavaScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To solve this problem, we can use a stack data structure to keep track of the indices of the bars in the histogram. This method helps us efficiently find the largest rectangle possible for each bar.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's the solution in JavaScript:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function largestRectangleArea(heights) {
  const stack = [];
  let maxArea = 0;

  for (let i = 0; i &lt;= heights.length; i++) {
    const h = i === heights.length ? 0 : heights[i];
    while (stack.length > 0 &amp;&amp; h &lt; heights[stack[stack.length - 1]]) {
      const height = heights[stack.pop()];
      const width = stack.length === 0 ? i : i - stack[stack.length - 1] - 1;
      maxArea = Math.max(maxArea, height * width);
    }
    stack.push(i);
  }

  return maxArea;
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>In this solution, we iterate through the input array <code>heights</code>. We maintain a stack to keep track of the indices of the bars in non-decreasing order of their heights. When we find a bar with a smaller height, we pop the elements from the stack and calculate the area of the rectangle that can be formed using the popped bar as the shortest one.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The time complexity of this solution is O(n) since we push and pop each element of the input array <code>heights</code> at most once. The space complexity is O(n) as we use a stack to store the indices of the bars.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In summary, this JavaScript solution has a time complexity of O(n) and space complexity of O(n) for the Largest Rectangle in a Histogram problem. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The solution provided above, with a time complexity of O(n) and space complexity of O(n), is considered optimal for the Largest Rectangle in a Histogram problem. It's unlikely that you would find a significantly more efficient algorithm in terms of time or space complexity.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The reason is that, in the worst case, you have to examine each bar in the histogram at least once to determine the largest rectangular area. This fact necessitates a lower-bound time complexity of O(n). The stack-based solution above takes advantage of this by maintaining a stack of indices, ensuring that each bar is only processed once.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="8-egg-dropping-problem">8. Egg Dropping Problem</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="8-1-problem-description">8.1 Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The Egg Dropping Problem is a classic problem in which you are given <code>n</code> eggs and a building with <code>k</code> floors. You need to determine the highest floor from which an egg can be dropped without breaking. The objective is to find the minimum number of attempts needed to find the solution.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="8-2-solution-in-java-script">8.2 Solution in JavaScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The Egg Dropping Problem can be solved using dynamic programming. The idea is to use a 2D array <code>dp</code>, where <code>dp[i][j]</code> represents the minimum number of attempts required to find the highest floor from which an egg can be dropped without breaking, given <code>i</code> eggs and <code>j</code> floors.</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function eggDrop(n, k) {
  const dp = Array(n + 1)
    .fill()
    .map(() => Array(k + 1).fill(0));

  for (let i = 1; i &lt;= n; i++) {
    dp[i][1] = 1;
    dp[i][0] = 0;
  }

  for (let j = 1; j &lt;= k; j++) {
    dp[1][j] = j;
  }

  for (let i = 2; i &lt;= n; i++) {
    for (let j = 2; j &lt;= k; j++) {
      dp[i][j] = Infinity;
      for (let x = 1; x &lt;= j; x++) {
        const res = 1 + Math.max(dp[i - 1][x - 1], dp[i][j - x]);
        dp[i][j] = Math.min(dp[i][j], res);
      }
    }
  }

  return dp[n][k];
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>The time complexity of this solution is O(n * k^2), and the space complexity is O(n * k). However, it is possible to optimize this solution further by using binary search instead of a linear search for the inner loop. This will reduce the time complexity to O(n * k * log(k)).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Overall, the Egg Dropping Problem is a challenging problem that can be solved using dynamic programming. By breaking down the problem into smaller subproblems and solving each subproblem only once, we can find the optimal solution and minimize the number of attempts needed to find the highest floor from which an egg can be dropped without breaking.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="9-counting-bits">9. Counting Bits</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="9-1-problem-description">9.1 Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Given a non-negative integer <code>num</code>, for every number <code>i</code> in the range <code>0 ≤ i ≤ num</code> calculate the number of 1's in their binary representation and return them as an array.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="9-2-solution-in-java-script">9.2 Solution in JavaScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We can solve this problem by using dynamic programming. We can start by initializing an array of length <code>num+1</code> with all values set to zero. Then, for each index <code>i</code> from 1 to <code>num</code>, we can update the value at <code>i</code> to be equal to the value at <code>i</code> divided by 2 plus the remainder of <code>i</code> divided by 2. This works because the number of 1's in the binary representation of a number <code>i</code> is equal to the number of 1's in the binary representation of <code>i/2</code> plus 1 if <code>i</code> is odd, or 0 if <code>i</code> is even.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here is the JavaScript code for this solution:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function countBits(num) {
  const dp = new Array(num + 1).fill(0);
  for (let i = 1; i &lt;= num; i++) {
    dp[i] = dp[Math.floor(i / 2)] + (i % 2);
  }
  return dp;
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>The time complexity of this solution is O(n), where <code>n</code> is the input number <code>num</code>. This is because we loop through all numbers from 1 to <code>num</code>. The space complexity is also O(n), because we use an array of length <code>num+1</code> to store the number of 1's for each number.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Overall, this is a simple and efficient solution to the counting bits problem, and it demonstrates the power of dynamic programming in solving algorithmic challenges.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="10-perfect-squares">10. Perfect Squares</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="10-1-problem-description">10.1 Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Given a positive integer <code>n</code>, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum up to <code>n</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="10-2-solution-in-java-script">10.2 Solution in JavaScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To solve this problem, we can use dynamic programming. We can create an array <code>dp</code> where <code>dp[i]</code> will store the least number of perfect square numbers that sum up to <code>i</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Initially, we can set all the elements of the <code>dp</code> array to Infinity except the first element, which will be 0. This is because if <code>n</code> is 0, then there are no perfect squares that sum up to it, and if <code>n</code> is 1, then the least number of perfect squares that sum up to it is 1.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can then iterate through all the numbers from 1 to <code>n</code> and for each number <code>i</code>, we can check all the perfect squares that are less than or equal to <code>i</code>. We can then update the value of <code>dp[i]</code> as the minimum of <code>dp[i]</code> and <code>dp[i - j*j] + 1</code>, where <code>j*j</code> is a perfect square less than or equal to <code>i</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Finally, we can return the value of <code>dp[n]</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here is the JavaScript code for the solution:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function numSquares(n) {
  const dp = Array(n + 1).fill(Infinity);
  dp[0] = 0;

  for (let i = 1; i &lt;= n; i++) {
    for (let j = 1; j * j &lt;= i; j++) {
      dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
    }
  }

  return dp[n];
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>The time complexity of this solution is O(n*sqrt(n)) and the space complexity is O(n).</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:heading -->
<h2 class="wp-block-heading" id="11-unique-paths">11. Unique Paths</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="problem-description">Problem Description</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Suppose you have a <code>m x n</code> grid. You can move either down or right at any point in time. You are trying to reach the bottom-right corner of the grid. How many unique paths are there?</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading" id="solution-in-java-script">Solution in JavaScript</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We can use dynamic programming to solve this problem. We start by initializing a 2D array <code>dp</code> of size <code>m x n</code>, where <code>dp[i][j]</code> represents the number of unique paths to reach the cell at <code>(i,j)</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can fill in the first row and first column of the <code>dp</code> array with 1, because there is only one way to reach any cell in the first row or column. Then, for all other cells, the number of unique paths is the sum of the number of unique paths to reach the cell directly above and the cell directly to the left.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Finally, the value of <code>dp[m-1][n-1]</code> represents the number of unique paths to reach the bottom-right corner of the grid.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's the JavaScript code for the solution:</p>
<!-- /wp:paragraph -->

<!-- wp:prismatic/blocks {"className":"no-trans prism-editor"} -->
<pre class="wp-block-prismatic-blocks no-trans prism-editor"><code class="language-">function uniquePaths(m, n) {
  const dp = Array(m).fill().map(() => Array(n).fill(1));
  
  for (let i = 1; i &lt; m; i++) {
    for (let j = 1; j &lt; n; j++) {
      dp[i][j] = dp[i-1][j] + dp[i][j-1];
    }
  }
  
  return dp[m-1][n-1];
}
</code></pre>
<!-- /wp:prismatic/blocks -->

<!-- wp:paragraph -->
<p>The time complexity of this solution is O(m * n), because we need to fill in each cell of the <code>dp</code> array exactly once. The space complexity is also O(m * n), because we are using a 2D array to store the values of <code>dp</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:spacer -->
<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->