<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Algorithms Digest - Medium]]></title>
        <description><![CDATA[Interesting techniques, strategies and problems for competitive and Leetcode programming explained in an intuitive manner. - Medium]]></description>
        <link>https://medium.com/algorithms-digest?source=rss----c9d867842f5d---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Algorithms Digest - Medium</title>
            <link>https://medium.com/algorithms-digest?source=rss----c9d867842f5d---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:55:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/algorithms-digest" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Previous Smaller Element]]></title>
            <link>https://medium.com/algorithms-digest/previous-smaller-element-e3996fb8be3c?source=rss----c9d867842f5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/e3996fb8be3c</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[next-greater-element]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Algorithms Digest]]></dc:creator>
            <pubDate>Mon, 10 May 2021 23:46:10 GMT</pubDate>
            <atom:updated>2021-05-10T23:45:28.554Z</atom:updated>
            <content:encoded><![CDATA[<h4>Similar To Leetcode #503 (Medium)</h4><h3>Introduction</h3><p>This blog post covers a variation of the <a href="https://leetcode.com/problems/next-greater-element-ii/">Next Greater Element II problem</a> on Leetcode. It is one of the problems which requires very clever use of a simple data structure. Moreover, this technique is used in several other Leetcode problems such as <a href="https://leetcode.com/problems/largest-rectangle-in-histogram/">Largest Rectangle In Histogram</a> and <a href="https://leetcode.com/problems/maximal-rectangle/">Maximal Rectangle</a> as a sub-routine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K9f5T5MoyFtbxhDz" /></figure><h3>Problem Statement</h3><blockquote>Given an array nums, return <em>the </em><strong><em>previous smaller number (PSE) </em></strong><em>for every element in</em> nums.</blockquote><blockquote>The <strong><em>previous smaller number</em></strong> of an element x is the first number (highest index) to the left of x that is smaller than x. If there’s no such element, return -1 for this number.</blockquote><p>Suppose nums[] = {9, 6, 10, 9, 5}.<br>The previous smaller elements (PSE) are as follows:<br>PSE of 9 is -1 (no element to the left of 9 that is smaller).<br>PSE of 6 is -1 (no element to the left of 9 that is smaller).<br>PSE of 10 is 6.<br>PSE of 9 is 6.<br>PSE of 5 is 6.</p><h3>Thought Process</h3><p>It’s easy to come up with a naive algorithm for the problem. <br>For an element at index i, we start scanning elements from index (i-1) to index 0 and select the first element which is smaller than nums[i].<br>Since there are n elements, and for each element, we are iterating over n elements to the left in the worst case, the overall runtime is O(n²).</p><p>However, Leetcode problems are seldom that simple. <br>n can be as large as 10⁴ which means that an O(n²) time algorithm will be too slow. <br>The challenge is to optimize the runtime.</p><p><strong>To optimize, we should figure out what’s the redundant computation that the algorithm is doing and try to eliminate it.</strong></p><p>Let’s dig in!</p><p>Suppose our array has 5 elements [1, 14, 12, 10, 4] and we know the index of the next smaller element to the left for 1, 14, 12, and 10.</p><p>Do we need to iterate over the entire array to figure out the previous smaller element for 4? <br>No!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*X8ZqBhSORBRsCT48n0z4oQ.png" /><figcaption>Skipping over elements by making use of the previous smaller elements already known. The lines indicate following the PSE of earlier numbers to compute the PSE of the current number.</figcaption></figure><ul><li>We know that the element on the immediate left of 4 i.e. 10 &gt; 4. Thus, 10 is not the previous smaller element for 4.</li><li>We also know that the previous smaller element of 10 is 1. So, we don’t need to compare 4 with 12 and 14, because we already know that everything between 10 and 1 is greater than 10 and hence also greater than 4.</li></ul><p>We were able to skip over 14 and 12 because there’s no point in looking at elements that are bigger than 10.</p><p><strong>In essence, instead of iterating through each element, we can skip elements by jumping over to the previous smaller elements. This avoids redundant computation. (KEY POINT 1)</strong></p><p>Great! We were able to identify and remove the redundant computation. <strong>But how should we implement this and does it actually improve the asymptotic runtime?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNgL59UiTvCYGm9PMYd0wg.png" /><figcaption>PSE for elements to the right of X will either be X, Y, or an element to the left of Y.</figcaption></figure><p>Say we’re moving from left to right in the array and computing the previous smaller element for each element.</p><p><strong>Notice that, when we encounter an element say X, everything to the left of X that is greater than X is meaningless since they’ll never be the previous smaller element for elements to the right of X. (KEY POINT 2)</strong></p><p>This hints towards using a stack. We want to push elements to the stack when we encounter them and pop elements that are of no use to us moving forwards.</p><h3>Algorithm</h3><ol><li>Initialize an empty stack. We will push element indices onto this.</li><li>Traverse the array from left to right. When you encounter an element X, keep popping indices from the stack as long as the value at that index is bigger than X (because they’re of no use to use anymore — see Keypoint 2).</li><li>If the stack becomes empty, there is no element on the left smaller than X.</li><li>If the stack isn’t empty, the index on top of the stack corresponds to the previous smaller element of X. Note this information in an array PS[].</li><li>Push index of element X onto the stack.</li></ol><p><strong>Why does this work? </strong><br>Suppose the previous smaller element of X is Y.<br>When we push X onto the stack, we are guaranteed that the index of Y is already present somewhere in the stack.</p><p>This is because:</p><ul><li>When we encountered Y, we must have pushed it onto the stack.</li><li>Since there is no element between Y and X that is smaller than X and Y (remember Y is the previous smaller element of X), Y could not have been popped from the stack.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrLAwUfbuMut2ssMlL02lQ.png" /></figure><p>Moreover, since everything between Y and X is greater than X, our algorithm will pop all of them from the stack till we have Y left at the top. At this point, we’ll set Y to be the previous smaller element of X.<br>If the stack is empty, that means there is no element smaller than X to its left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*bJfv3aT5PfMWhZShZpCSrg.png" /><figcaption>Dry-run of the algorithm on the array [1, 14, 12, 10, 4]. Note that the red boxes indicate the elements that are popped from the stack when the element to be inserted is smaller than the top stack element.</figcaption></figure><h3>Runtime Analysis</h3><p>When dealing with stacks, it’s good to think about runtime in terms of the number of push/pop operations. <br>In this case, no element is re-inserted into the stack. Hence, each element is pushed onto the stack once and popped at most once. Thus, we have O(n) push/pop operations.<br>Moreover, before every pop operation, we just do an O(1) comparison with the stack top. Thus, the overall runtime is O(n).</p><h3>Follow-Ups</h3><p>In this post, we have covered how to compute the previous smaller element. But if you understand the concept, it can be easily applied to variations such as the previous larger element and the next smaller/greater element.<br>Think about how to do this as an exercise!</p><p>Moreover, this can be applied to other Leetcode problems as well such as <a href="https://leetcode.com/problems/largest-rectangle-in-histogram/">Largest Rectangle In Histogram</a> and <a href="https://leetcode.com/problems/maximal-rectangle/">Maximal Rectangle</a>. Here’s a <a href="https://algorithms-digest.medium.com/largest-rectangle-in-histogram-234004ecd15a">blog post </a>explaining the Largest Rectangle in Histogram problem.</p><p>Please endorse the article and let me know in the comments if this explanation helped you understand the problem better. Would love to hear any feedback/suggestions/edits as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3996fb8be3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algorithms-digest/previous-smaller-element-e3996fb8be3c">Previous Smaller Element</a> was originally published in <a href="https://medium.com/algorithms-digest">Algorithms Digest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Largest Rectangle in Histogram]]></title>
            <link>https://medium.com/algorithms-digest/largest-rectangle-in-histogram-234004ecd15a?source=rss----c9d867842f5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/234004ecd15a</guid>
            <category><![CDATA[next-greater-element]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Algorithms Digest]]></dc:creator>
            <pubDate>Mon, 10 May 2021 23:46:03 GMT</pubDate>
            <atom:updated>2021-05-18T01:16:14.475Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leetcode Problem #84 (Hard)</h4><h3>Introduction</h3><p>This post covers the Largest Rectangle in Histogram problem on Leetcode. <br>The challenge is not in figuring out how to solve the problem but rather to figure out how to optimize the runtime. It’s a direct application of the technique used in Previous Smaller Element as covered in this <a href="https://algorithms-digest.medium.com/previous-smaller-element-e3996fb8be3c">blog post</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SRE4Nj8M3sI78acV" /></figure><h3>Problem Statement</h3><blockquote>Given an array of integers heights representing the histogram&#39;s bar height where the width of each bar is 1, return <em>the area of the largest rectangle in the histogram</em>.</blockquote><p>Imagine having rectangular blocks arranged in a straight line. Each block has a width of 1 unit and the i-th block has a height of heights[i] units. <br>The goal is to find a rectangle, potentially spanning across multiple bars with the maximum area.</p><p>Suppose input is[2, 1, 5, 6, 2, 3]. This can be visually represented as shown in the figure below.<br>We can rectangles in multiple ways as shown in the figure. However, the rectangle with the maximum area is the one with a height of 5 units spanning across bars at index 2 and index 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1x-nAWU8lB4YfiyTe5HkQ.png" /><figcaption>A few of the possible rectangles that can be drawn are outlined in red. The figure on the right shows the rectangle with the maximum possible area i.e. 10 units.</figcaption></figure><h3>Thought Process</h3><p>It’s important to think about what the rectangle with the maximum area looks like.<br><strong>A key observation should be that the height of the maximal rectangle will be equal to the height of one of the included bars.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_roasotgBncAZYeSlqciA.png" /></figure><p>Why?<br>Because, if all the bars included in the rectangle are taller than the height of the rectangle, the rectangle’s height can be increased and we get a bigger area. This contradicts the assumption that the rectangle we started with has the maximum area.</p><p><strong>In fact, the height of the maximal rectangle will be equal to the shortest bar included in it.</strong> Otherwise, the rectangle wouldn’t be valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*hpt21ilNdifvCNAn" /><figcaption>Rectangle can’t be valid because it will always lie over the shortest bar’s height.</figcaption></figure><p><strong>We can focus our attention on rectangles whose height is equal to the shortest bar included in it.</strong><br>This gives us a way to search for the maximal rectangle.</p><p><strong>For each bar, compute the maximal rectangle which includes that bar and the height of the rectangle is equal to the bar’s height (i.e. it is the shortest bar included).</strong></p><h3>Algorithm</h3><h4>Algorithm 1 (Naive):</h4><p>For each bar (say with height H), compute how many bars on the immediate left are taller than H, let’s say that is L. Similarly, compute how many bars in the immediate right are taller than H, let’s say that is R.<br>Then, the height of the maximal rectangle with height H that includes this bar is equal to H * (R + L + 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jtik5XcFb7DK0TvQFTrIoA.png" /></figure><p>We can repeat this for each bar and select the one which gives the maximum area!</p><p>If we have O(n) bars, the above algorithm will take O(n²) time. This is because, for each bar, computing L and R requires a scan to the left/right which takes O(n) in the worst case (for example when all the bars have the same height).</p><h4>Algorithm 2 (Optimized):</h4><p>The challenge is to optimize the runtime of our algorithm.<br>In Algorithm 1, for each bar we do O(n) amount of work by scanning to the left and right.<br>We need to think about how to optimize finding L and R.</p><p>Note that finding L for some bar X is equivalent to finding the index of the first element to the left of X that is smaller than X (say lIndex). <br>Similarly, finding R is equivalent to finding the index of the first element to the right of X that is larger than X (say rIndex).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9v_bO-f_CReZhtd4nylOw.png" /><figcaption>Finding L and R is equivalent to finding the index of the previous smaller element and the next smaller element.</figcaption></figure><p>Figuring out the previous smaller element is an independent problem in itself. It’s covered in this blog post: <a href="https://algorithms-digest.medium.com/previous-smaller-element-e3996fb8be3c">Previous Smaller Element.</a></p><p>It explains how we can compute the previous smaller element for every element in the array in a total of O(n) time.</p><p>Finding the next greater element is very similar, it’s like finding the previous smaller element in the reversed array. Hence, we can use the same technique.</p><p>Thus, our algorithm is as follows:</p><p>For the bar at index i,</p><ol><li>Compute the index of the previous smaller element on the left. Let’s call this lIndex. If there’s no smaller element on the left, set lIndex to i-1.</li><li>Compute the index of the next smaller element on the right. Let’s call this rIndex. If there’s no smaller element on the right, set rIndex to i+1.</li><li>This means that we can include all bars with index in the range [lIndex+1, rIndex-1] i.e. rIndex - lIndex -1 bars.</li><li>Thus, the maximum rectangle which includes this bar as the shortest bar has an area of ( rIndex - lIndex -1 ) * nums[i].</li></ol><p>Repeat this for each index i and keep track of the overall maximum. That’s the final answer.</p><h3>Runtime Analysis</h3><p>Computing L (or lIndex) and R (or rIndex) for each element takes overall O(n) time as describe <strong>here</strong>. After that, for each bar, computing the maximum area with that bar as the smallest takes O(1) time. Thus, the overall runtime is O(n).</p><p>Please endorse the article and let me know in the comments if this explanation helped you understand the problem better. Would love to hear any feedback/suggestions/edits as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=234004ecd15a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algorithms-digest/largest-rectangle-in-histogram-234004ecd15a">Largest Rectangle in Histogram</a> was originally published in <a href="https://medium.com/algorithms-digest">Algorithms Digest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shortest Path in a Grid with Obstacles Elimination]]></title>
            <link>https://medium.com/algorithms-digest/shortest-path-in-a-grid-with-obstacles-elimination-ad0c07ed41c2?source=rss----c9d867842f5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad0c07ed41c2</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[graph-algorithms]]></category>
            <category><![CDATA[shortest-path]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <dc:creator><![CDATA[Algorithms Digest]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 00:39:27 GMT</pubDate>
            <atom:updated>2021-05-09T01:48:17.582Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leetcode Problem #1293 (Hard)</h4><h3>Introduction</h3><p>This blog post covers the <a href="https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/">Shortest Path In A Grid With Obstacles Elimination problem</a> on Leetcode.<br>This problem illustrates how a standard graph traversal algorithm can solve a tricky problem if we smartly encode multiple parameters into the graph state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tDnEDqsWlw8l0n7b" /></figure><h3>Problem Statement</h3><blockquote>You are given an m x n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell.</blockquote><blockquote>Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate <strong>at most</strong> k obstacles. If it is not possible to find such a walk return -1.</blockquote><p>We need to find the shortest path from the top-left corner to the bottom-right corner. The only condition is that some cells are blocked and we are allowed to pass through at-most k blocked cells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWwJMXsm83blGWp6nLdyDg.png" /></figure><h3>Thought Process / Intuition</h3><p>Let’s take a step back<br>Suppose that we need to find the shortest path from (0, 0) to (m-1, n-1) in the grid where some of the cells are blocked (have obstacles). Assume that we CANNOT destroy any obstacles.</p><p>This is a standard graph problem that can be solved using BFS.</p><ol><li>For each cell in the grid, create a node in the graph representing the cell position (x, y).</li><li>Add an undirected edge between noodes corresponding to each pair of adjacent cells if neither of them are blocked.</li><li>Use BFS starting from node (0, 0) to find the shortest path to (m-1, n-1).</li></ol><p>If we are allowed to destroy obstacles, we might be able to find a shorter path.</p><p>How do we incorporate the fact that we can destroy k obstacles?</p><p>In the simplified problem described above, each node in the graph denoted a position (x, y) in the grid. <br><strong>But, along with the position, we also want to track how many obstacles we have destroyed so far.</strong></p><p>Let’s try to do that.<br>Imagine that we have (k+1) copies of the grid stacked on top of each other. The x-axis and y-axis will represent the positions in the grid. Additionally, let’s say that being at the<strong> </strong><strong>i-th level grid</strong> means that we have <strong>destroyed </strong><strong>i obstacles </strong>so far.</p><p>Since we start at position (0, 0) and we haven’t destroyed any obstacles yet it is equivalent to starting at position (0, 0) at the 0-th level grid.</p><p>If we are at position (x, y) in the 0-th level grid, we can move to an adjacent unblocked cell in the same grid, say (x+1, y). This is because we can move to (x+1, y) without destroying any obstacle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*8JhZ1ntXbRNSjrV4M-c-8w.png" /><figcaption>Cell connected to adjacent unblocked nodes at the same level and adjacent. blocked cells at the level above.</figcaption></figure><p>Alternatively, if we want to move to an adjacent blocked cell, it means that we have to destroy an obstacle. So, our position changes to (x+1, y) but since we have destroyed an obstacle, we need to move one level up. This is equivalent to moving to position (x+1, y) in the 1-st level grid.</p><p>If you understand the above concept, it is not hard to generalize this.<br>Each node will be connected to:</p><ul><li>Adjacent unblocked cells at the same level.</li><li>Adjacent blocked cells at the level just above (simulating obstacle destruction).</li></ul><p><strong>Note how at the last level of the grid, we will not be able to move to any blocked cells as there is no level above this one. This is equivalent to having destroyed all the </strong><strong>k obstacles we could have.</strong></p><p>As mentioned earlier, our <strong>starting point will be </strong><strong>(0, 0) at the 0-th level grid. </strong><br><strong>Our destinations are the </strong><strong>(m-1, n-1) cells at ANY level.</strong> This is because we are allowed to destroy less than k obstacles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*4OnKv-OsRrZU7Bu8JICzAA.png" /><figcaption>Shortest path illustration when we are allowed to destroy one obstacle (k = 1).</figcaption></figure><p>Note that, the cells at the same level should be connected with undirected edges. However, the edges across levels should be directional i.e. we can go from a lower level to a higher level but cannot come down (since that would mean we are decreasing the count of destroyed obstacles).</p><p>We will run BFS from the starting point and find the shortest path to any of the destination cells.</p><h3>Algorithm</h3><p>To represent this concept of multiple grids, we only need a minor change in code.<br>Each node, instead of representing just a position(x, y) will now represent a triplet (x, y, d) indicating the position (x, y) and number of obstacles destroyed (d).</p><p>Pseudocode:</p><ol><li>Initialize empty queue Q.</li><li>Initialize 3D-array VISITED[m][n][k] to mark visited nodes.</li><li>Insert starting node (0, 0, 0) to Q.</li><li>Run BFS.</li><li>Return the distance to the first node discovered by BFS with position (m-1, n-1).</li><li>If no such node is reachable, return -1.</li></ol><h3>Runtime Analysis</h3><p>We are essentially constructing a graph with n * m * k nodes. Each node can have at most 4 edges (to adjacent unblocked nodes at the same level and blocked nodes at the higher level).</p><p>Thus, our graph has |V| = O(n * m * k) vertices and |E| = O(n * m * k) edges. <br>Then, we simply run BFS to find the shortest path which takes O(|V| + |E|) = O(n * m * k) time.</p><p>Please endorse the article and let me know in the comments if this explanation helped you understand the problem better. Would love to hear any feedback/suggestions/edits as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad0c07ed41c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algorithms-digest/shortest-path-in-a-grid-with-obstacles-elimination-ad0c07ed41c2">Shortest Path in a Grid with Obstacles Elimination</a> was originally published in <a href="https://medium.com/algorithms-digest">Algorithms Digest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predict The Winner]]></title>
            <link>https://medium.com/algorithms-digest/predict-the-winner-16668e9c1cb8?source=rss----c9d867842f5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/16668e9c1cb8</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[predict-the-winner]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Algorithms Digest]]></dc:creator>
            <pubDate>Wed, 21 Apr 2021 23:07:25 GMT</pubDate>
            <atom:updated>2024-01-20T05:33:17.292Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leetcode Problem #486 (Medium)</h4><h3>Introduction</h3><p>This blog post covers the <a href="https://leetcode.com/problems/predict-the-winner/">Predict The Winner problem on Leetcode</a>. It is a dynamic programming problem. The solution is not too hard once we know exactly what to compute.<br>T<strong>his post digs deeper into the problem statement to break it down and see how it leads to a DP solution. It also explains the DP formulation one step at a time.<br>Lastly, it describes a smart trick for an O(1) solution for special cases.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ghA_xktjyguSwQgP" /></figure><h3>Problem Statement</h3><blockquote>You are given an integer array nums of size n. Two players are playing a game with this array: player 1 and player 2.</blockquote><blockquote>Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array.</blockquote><blockquote>Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.</blockquote><p>In simpler words, in each turn, the player whose turn it is, picks a number from either end of the array. The number gets added to that player’s total score.<br>The players pick numbers turn-by-turn till no more numbers are left. The player with the higher score wins.</p><p>Let’s look at an example.<br><strong>Input: </strong>nums = {5, 1, 7, 10}</p><p>Here are some possible game sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYTMeOE9zexStthZDRL1Yg.png" /><figcaption>Game Sequence 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsUXkyM6A36KjYDn0dAgZA.png" /><figcaption>Game Sequence 2</figcaption></figure><p>The game is simple enough to understand but predicting the winner is tricky. We need to dig into a few details about the problem statement before we try and think about an algorithm.</p><ol><li>What does <em>‘Player 1 </em><strong><em>can win</em></strong><em> the game’</em> mean?</li><li>What does <em>‘playing optimally’</em> mean?</li></ol><h3>Thought Process / Intuition</h3><h4>DISSECTING THE PROBLEM STATEMENT</h4><p>Let’s think about the above two points.</p><p>The problem is not asking whether there is a possibility of Player 1 winning the game out of all possible game sequences/strategies that Player 2 might use. <br>It clearly specifies that <strong>Player 2 is playing the game optimally.</strong></p><p>But what does playing optimally mean?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jsUpJboXLEQ_bdBx" /></figure><p>Since Player 2 wants to win the game, it is optimal for Player 2 to try and maximize its score.<strong> If Player 1 wants to win, it should also play optimally.</strong></p><p><strong>In other words, both players will make the move which maximizes their final score (assuming that the other player is also playing with that in mind).</strong></p><p>Now, to check if Player 1 can win, we want to see if the maximum score that Player 1 can obtain is big enough to win.</p><p>At this point, the problem is starting to look like an optimization problem. <br><strong>‘Given a game state, what is the maximum score that Player 1 can obtain assuming that Player 2 also plays optimally’.</strong></p><h4>GREEDY VS DP</h4><p>Knowing that this is an optimization problem (score maximization), should be a hint that we need a greedy or DP algorithm.</p><p>It’s always a good idea to think about a few greedy strategies as a preliminary check and see whether they work.</p><p>Some greedy strategies could be:</p><ul><li>Select the coin with maximum value out of the available choices.<br>Doesn’t work for {5, 4, 9, 7} (See Game Sequence 1). The greedy solution gives 12 (7+5) points to Player 1 and 13 points (9+4) to Player 2. <br>Instead, if Player 1 picked 5 in the first round, it could get 14 points and beat Player 2.<br>This is intuitive, picking a bigger number initially might make an even bigger number available to Player 2.</li><li>To avoid the risk of exposing a bigger number, one might propose to make a greedy choice that maximizes points in the next 2 steps. However, it leads to the same problem because we are still looking just 2 steps ahead instead of nsteps.</li></ul><p>This preliminary check is no guarantee that a greedy solution doesn’t exist. But since these ones don’t work, we are tempted to consider a DP solution.</p><h4><strong>DP FORMULATION</strong></h4><p>To formulate a DP algorithm, we must think about what the <strong>sub-problems </strong>should be and how they can be <strong>recursively computed.</strong></p><p>From experience, the <strong>sub-problems for arrays are subsets of the array.</strong></p><p>The recursive relationship can be figured out by <strong>thinking about the choices we make to construct our solution.<br></strong>In this case, we are picking numbers, so the choice could be <strong>‘Which number was picked — the one at the start or the one at the end?’.</strong></p><p>Now,</p><ul><li>We are picking/removing elements from either end of the array, hence the game state at any instant is a sub-array of the original array.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iDBcHTvbtOEIXDyCDYLOA.png" /><figcaption>Since the players can only pick elements from either end of the array, the game state is always going to be a sub-array of the original array.</figcaption></figure><ul><li>Our goal is to find the maximum score that the player can score given a game state.</li></ul><p>Hence, we can define the sub-problems with a 2D array (DP[][]) such that DP[i,j] represents the maximum coins that can be collected by Player 1 considering the array nums[i…j].</p><p>Now, let’s compute DP[i,j]. There are 2 choices for Player 1 — pick nums[i] or pick nums[j].</p><p><strong>Choice 1:</strong><br>If Player 1 picks nums[i], nums[i] is added to the score and the game state nums[(i+1)...j] is given to Player 2. We know that Player 2 plays optimally as well so it will maximize its score for the game state presented which is DP[(i+1), j]. This leaves the remaining numbers for Player 1 i.e. (nums[i+1] + nums[i+2] + … + nums[j]) - DP[(i+1), j].</p><p><strong>Choice 2:</strong><br>If Player 1 picks nums[j], nums[j] is added to the score and the game state nums[(i...(j-1)] is given to Player 2. We know that Player 2 plays optimally as well so it will maximize its score for the game state presented which is DP[i, (j-1)]. This leaves the remaining numbers for Player 1 i.e. (nums[i] + nums[i+1] + … + nums[j-1]) - DP[i, (j-1)].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESNMzWrJCPAdTnA0bwBJ_Q.png" /></figure><p>Player 1 will make the choice which will maximize its score i.e. the maximum of both the situations described above.</p><p>A simple hack to avoid computing the sum of values in the resulting subarrays is to compute the cumulative sums. Let cumulativeSum[] be a 1D array such that cumulativeSum[i] = nums[0] + nums[1] + ... + nums[i].</p><p>Then, DP[i, j] = Max {nums[i] + (cumulativeSum[j] - cumulativeSum[i+1] + nums[i+1]) - DP[(i+1), j], nums[j] + (cumulativeSum[j-1] - cumulativeSum[i] + nums[i]) - DP[i, j-1] }.</p><p>Note that computing the optimal value for a subarray depends on the solution to smaller subarrays. Thus, we will compute the entries to the DP table in a bottom-up manner filling out entries corresponding to subarrays of size 1, then size 2, and so on.</p><p>Our base case can be subarrays of size 1 and size 2. <br>For size 1 sub-array, Player 1 gets the only number available and Player 2 scores 0.<br>For sub-arrays of size 2, Player 1 gets the maximum of the two numbers and Player 2 gets the other one.</p><p>Finally, the maximum score obtainable by Player 1 is DP[0, (n-1)]. Is this enough to win? We simply compare DP[0, (n-1)] to (Sum Of All Elements In nums[0]) — DP[0, (n-1)] i.e. we return DP[0, (n-1)] ≥ cumulativeSum[n-1] — DP[0, (n-1)].</p><h3>Algorithm</h3><p>To summarise the discussion above:</p><ol><li>Define DP[n][n] such that DP[i][j] (j &gt; i) represents the maximum points scored by the first player playing with the game state nums[i...j].</li><li>Define cumulativeSum[]such that cumulativeSum[i] = nums[0] + nums[1] + … + nums[i].</li><li>(Base Case) DP[i][i] = nums[i]and DP[i][i+1] = Max( nums[i], nums[i+1] ) because the first player will pick the bigger number.</li><li>DP[i, j] = Max ( nums[i] + cumulativeSum[j] - cumulativeSum[i+1] + nums[i+1]- DP[(i+1), j], nums[j] + cumulativeSum[j-1] - cumulativeSum[i] + nums[i]- DP[i, j-1] )</li><li>Final answer is DP[0, (n-1)] ≥ cumulativeSum[n-1] — DP[0, (n-1)].</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54972e647605cfd697398662b896e1e6/href">https://medium.com/media/54972e647605cfd697398662b896e1e6/href</a></iframe><p>Here’s a quick walk-through of filling out the DP table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1x7l11qzV9Jq-mRCWEzA3w.png" /></figure><p>In this case, Player 1 can score a maximum of 14 points (DP[0][3]). <br>14 ≥ 11 (5+4+9+7–14) and hence Player 1 can win.</p><p>We compute the DP entries for cells on the diagnal followed by cells that are distance 1 from the diagonal, then distance 2 and finally distance 3.</p><h3>Runtime Analysis</h3><p>Computing the cumulative sums array takes O(n) time.</p><p>Our 2D DP table has O(N²) entries. To compute each entry, we are looking at two possible choices that Player 1 can make. For each choice, computing the maximum score takes O(1) time.<br>Thus, computing each entry of DP[][] takes O(1)time.<br>Hence, the overall runtime is O(N²) x O(1) = O(N²).</p><p>Check out the section below for a cool trick that solves the problem in O(1) for special cases.</p><h3>Bonus: Trick For Arrays Of Even Length</h3><p>If n(size of the array) is even, then it is guaranteed that Player 1 can win.</p><p><strong>Why? <br></strong>Because Player 1 can decide to select all the numbers at odd positions (forcing Player 2 to take the even positions) or select all the numbers at even positions (forcing Player 2 to take the odd positions).</p><p>Player 1 can compute if the odd positioned numbers give a higher score or the even positioned ones and select the strategy accordingly.</p><p><strong>How?<br></strong>Suppose that Player 1 wants to pick the even indexed numbers. <br>The first move will be to select nums[0].<br>Now, notice that the numbers available to Player 2 are nums[1] and nums[n-1] (odd-indexed).<br>Whichever one Player 2 chooses, it will expose an even indexed number for Player 1 to pick again leaving Player 2 with odd-indexed numbers.</p><p>Similarly, to get all the odd indexed numbers, Player 1 can start with nums[n-1] and then follow a similar strategy as above.</p><p>You can simply <strong>return true if n is even</strong> to speed up the runtime.</p><p>Please endorse the article and let me know in the comments if this explanation helped you understand the problem better. Would love to hear any feedback/suggestions/edits as well.</p><p>Can’t get enough of DP? Check out these articles.</p><ul><li><a href="https://algorithms-digest.medium.com/maximal-square-e0ba64fbebb6">Maximal Square (Leetcode #221)</a></li><li><a href="https://medium.com/algorithms-digest/bursting-balloons-1820664a4ffa">Bursting Balloons (Leetcode #312)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16668e9c1cb8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algorithms-digest/predict-the-winner-16668e9c1cb8">Predict The Winner</a> was originally published in <a href="https://medium.com/algorithms-digest">Algorithms Digest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bursting Balloons]]></title>
            <link>https://medium.com/algorithms-digest/bursting-balloons-1820664a4ffa?source=rss----c9d867842f5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/1820664a4ffa</guid>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[burst-balloons]]></category>
            <dc:creator><![CDATA[Algorithms Digest]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 18:09:45 GMT</pubDate>
            <atom:updated>2024-01-20T05:31:15.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leetcode Problem #312 (Hard)</h4><h3>Introduction</h3><p>This blog post covers the <a href="https://leetcode.com/problems/burst-balloons/">Bursting Balloons problem on Leetcode</a>. It is a dynamic programming problem in which coming up with the sub-problem definition is hard.<br>Instead of directly explaining the solution, <strong>this post goes through the thought process of formulating the DP solution in a step-by-step manner.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_pFKux5VXRom4VdC" /></figure><h3>Problem Statement</h3><blockquote>You are given <em>n</em> balloons, indexed from <em>0</em> to <em>n - 1</em>. Each balloon is painted with a number on it represented by an array <em>nums</em>. You are asked to burst all the balloons.</blockquote><blockquote>If you burst the <em>ith</em> balloon, you will get <em>nums[i - 1] * nums[i] * nums[i + 1]</em> coins. If <em>i - 1</em> or <em>i + 1</em> goes out of bounds of the array, then treat it as if there is a balloon with a <em>1</em> painted on it.</blockquote><blockquote>Return <em>the maximum coins you can collect by bursting the balloons wisely</em>.</blockquote><p>Let’s look at an example to understand this.<br><strong>Input: </strong>nums = {5, 2, 4, 9}</p><p>There are multiple sequences in which we may burst the balloons. <br>Say we burst the balloons in this order: [2, 4, 9, 5]. This is what the steps would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qf-SYEMDbE19lGJ42NgIHQ.png" /></figure><p>However, the optimal sequence (to maximize coins collected) would be [2, 4, 5, 9]. The steps for this would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYYSRKE0kiUmWZJ8Qph1sw.png" /></figure><h3>Thought Process / Intuition</h3><h4>GREEDY VS DP</h4><p>This is an optimization problem (coin maximization) and we’re trying to select the best ordering. This is usually a hint that we need a greedy or DP algorithm.</p><p>Some greedy strategies could be:</p><ul><li>Burst the balloon which maximizes the coins collected that step.<br>Doesn’t work for {2, 9, 2}. Greedy solution (9, 2, 2) gives 42 coins whereas we can get 45 coins with (2, 2, 9).</li><li>Burst the smallest balloon since that allows the bigger numbers to be utilized multiple times.<br>Doesn’t work for {2, 3, 4}. Greedy solution (2, 3, 4) gives 22 coins whereas we can get 36 coins with (3, 2, 4).</li></ul><p>This preliminary check is no guarantee that a greedy solution doesn’t exist. But since these ones don’t work, we are tempted to consider a DP solution.</p><h4><strong>DP FORMULATION</strong></h4><p>To formulate a DP algorithm, we must think about what the <strong>sub-problems </strong>should be and how they can be <strong>recursively computed.</strong></p><p>From experience, the <strong>sub-problems for arrays are subsets of the array.</strong></p><p>The recursive relationship can be figured out by <strong>thinking about the choices we make to construct our solution.<br></strong>In this case, we burst balloons, so the choice could be <strong>‘Which balloon is burst first?’ </strong>or<strong> ‘Which balloon is burst last?’.</strong></p><p>We’ve got a basic idea. Let’s dig deeper! <br>We’ll start with a simple approach, see its limitations and modify it step by step to solve our problem.</p><p><strong>Idea 1: </strong>Define the sub-problems with a 1D array (DP[]) where DP[i] represents the optimal solution for the sub-array nums[0...i] and the recursive structure is based on what balloon we burst first.</p><p>To compute DP[i], we should iterate over the different choices we can make and choose the best one. But notice that while computing DP[i], if we burst the balloon at index j<em> , </em><strong>the resulting array cannot be represented by any of our subproblems</strong> (see below figure). In other words, balloon j-1 and balloon j+1 are dependent on each other (for calculating the profit) and so <strong>the array is not split into independent sub-problems.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TT4VkYmJ0iUVj4e_60e87g.png" /><figcaption>Limitation Of Idea 1.</figcaption></figure><p>This clearly won’t work.</p><p><strong>Idea 2: </strong>Instead, suppose that the recursive structure is based on which balloon is burst last. While computing DP[i], if the balloon at index j<em> </em>is burst last<em>, </em>we need to deal with the two parts that the balloons have been divided into.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWZDZ1FT93x4du7QkCpHCw.png" /><figcaption>Limitation Of Idea 2</figcaption></figure><p>This cannot be done with the current sub-problem definition since it doesn’t represent the array [(j+1)…(n-1)]. To deal with this, our subproblems need to represent subarrays between any two indices.</p><p><strong>Idea 3:</strong><br>Let’s say that DP[i,j] represents the maximum coins collected by considering balloons[i…j].<br>If the balloon at index <em>k</em> is the last one to burst, it means we need to first burst all balloons [i…(k-1)] and [(k+1)…j] and then burst the balloon at index k. This would give us DP[i][k-1] + DP[k+1][j] + (Coins on bursting balloon at index <em>k</em>).<br>Do you see the problem with this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPKKbNdHGHNMLPKzax5s1w.png" /><figcaption>Limitation Of Idea 3.</figcaption></figure><p><strong>We are computing </strong><strong>DP[i][k-1] and </strong><strong>DP[k+1][j]without considering the balloon at index k. </strong>Let’s try to deal with this by modifying the definition of DP[i,j].</p><p><strong>Idea 4: </strong>Let DP[i,j] represent the maximum coins collected by bursting balloons [(i+1)…(j-1)] i.e. we DO NOT burst the balloons on the extreme left and right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tTL7qcHFgs8Hs754koTAQ.png" /><figcaption>Idea 4 In Work</figcaption></figure><p>Now, when we burst the balloon at index <em>k</em>, we can get:</p><ul><li><strong>DP[i,k] </strong>(Maximum coins collected by bursting balloons[(i+1)…(k-1)])+</li><li><strong>DP[k,j] </strong>(Maximum coins collected by bursting balloons[(k+1)…(j-1)])+</li><li><strong>nums[i]*nums[k]*nums[j] </strong>(Coins collected on bursting the index k balloon (it’s surrounded by balloons i and j when everything else in between has been burst)).</li></ul><p><strong>Notice how by keeping the left-most and right-most balloon untouched we circumvent the dependency on balloons outside our range.</strong></p><p>To solve the original problem, we can assume that the original balloons are surrounded by balloons with value 1 on the left and right as this doesn’t change the answer in any way. <br>So, we create an array A[] = {1, nums[0], nums[1], …, nums[n-1], 1} (as shown below) of size n+2 over which we apply the DP algorithm described above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-cgTcY0yrwrC1mvFH9JoA.png" /><figcaption>Adding balloons with value 1 on the extreme left and right.</figcaption></figure><p>Our final answer will be DP[0, n+1].</p><h3>Algorithm</h3><p>To summarise the discussion above:</p><ol><li>Define <em>A[] = {1, nums[0], nums[1], …, nums[n-1], 1} </em>of size (n+2). Let these represent the balloons.</li><li>Define DP[n+2][n+2] such that DP[i][j] (j &gt; i) represents the maximum coins collected by bursting balloons [(i+1)…(j-1)].</li><li>(Base Case) DP[i][i+1] = 0 because we have no ballons to burst.</li><li>DP[i][j] = Max ( DP[i][k] + DP[k][j] + (nums[i]*nums[k]*nums[j]), (i+1)≤ k ≤ (j-1) ).</li><li>Final answer is DP[0,n+1].</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/385fce8123cd79e359c6ea6de8b05514/href">https://medium.com/media/385fce8123cd79e359c6ea6de8b05514/href</a></iframe><h3>Runtime Analysis</h3><p>Our 2D DP table has O(N²) entries. To compute each entry, we are looking at all the possible choices for the last balloon to be burst and taking the maximum one. There are O(N) choices in the worst case at each step and for each choice computing the coins collected is an O(1) operation. <br>Thus, computing each entry of DP[][] takes O(N) * O(1) = O(N) time.<br>Hence, the overall runtime is O(N²) x O(N) = O(N³).</p><p>Please endorse the article and let me know in the comments if this explanation helped you understand the problem better. Would love to hear any feedback/suggestions/edits as well.</p><p>Can’t get enough of DP? Check out these articles.</p><ul><li><a href="https://algorithms-digest.medium.com/maximal-square-e0ba64fbebb6">Maximal Square (Leetcode #221)</a></li><li><a href="https://medium.com/algorithms-digest/predict-the-winner-16668e9c1cb8">Predict The Winner (Leetcode #486)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1820664a4ffa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algorithms-digest/bursting-balloons-1820664a4ffa">Bursting Balloons</a> was originally published in <a href="https://medium.com/algorithms-digest">Algorithms Digest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coordinate Compression]]></title>
            <link>https://medium.com/algorithms-digest/coordinate-compression-2fff95326fb?source=rss----c9d867842f5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/2fff95326fb</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[segment-tree]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Algorithms Digest]]></dc:creator>
            <pubDate>Sun, 04 Apr 2021 22:30:07 GMT</pubDate>
            <atom:updated>2021-04-05T18:25:38.560Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dealing with huge arrays and large numbers</h4><h3>Introduction</h3><p>Coordinate compression is a technique to map a large set of points to a smaller range by removing gaps and/or redundant information. By compressing the points to a smaller range, we can save considerable time and memory.</p><p>Most of you would have unknowingly applied 1D coordinate compression but it’s 2D coordinate compression that is extremely powerful. This blog post explains both cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FB20nWpcGfcq3uHj" /></figure><h3>Coordinate Compression In 1D</h3><p>The simplest example of coordinate compression is sorting a 1D array. <br>Suppose we have an array A[] of size N. After sorting, the element A[i] is mapped to index i. This way, elements that were in an arbitrary range are now mapped to the range [0, N-1] and yet their relative ordering is preserved. <br>Sounds trivial? This proves to be very useful. Let’s check out an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*nAucVgQ-lckNQZHDIG1Gnw.png" /><figcaption>1D Coordinate Compression: Mapping an array of N numbers to the range [0, N-1].</figcaption></figure><h4>PROBLEM</h4><p>Given an array A[] of size N where 0 ≤ A[i] &lt;R. For each element A[i], count the number of elements to the left that are smaller than A[i].</p><p><strong>Example: </strong>A[] = {1, 5, 3, 7, 2}, N = 5.<br>The answer here would be [0, 1, 1, 3, 1].</p><h4>MAIN IDEA</h4><p>We will build a data structure that tracks the number of elements less than a particular value. We will then traverse A[] from the left and for each element A[i], insert A[i] into our data structure and query the number of elements smaller than A[i].</p><p>We can use segment trees for this. If you’re not familiar with segment trees, <a href="https://www.hackerearth.com/practice/data-structures/advanced-data-structures/segment-trees/tutorial/">here</a> is a good explanation. <br>The main idea is that a segment tree is built over an array of size N in O(N) time and each node stores a metric (say sum) corresponding to a continuous range in the original array. <br>This enables range sum queries (sum of elements in a range [L, R]) in O(logN) time and single element updates in O(logN) time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*clNwQM9-U0hRx6Id.jpg" /><figcaption>Segment Tree Structure (Reference: <a href="https://www.hackerearth.com/practice/data-structures/advanced-data-structures/segment-trees/tutorial/">https://www.hackerearth.com/practice/data-structures/advanced-data-structures/segment-trees/tutorial/</a>)</figcaption></figure><h4>ALGORITHM</h4><p>We will create an array Counts[] of size R initialized to 0 where Counts[<strong>x</strong>] indicates the occurrence count of value <strong>x</strong>. <br>We’ll build a segment tree on top of this where each node will store the sum of numbers in the corresponding range.</p><p>We will traverse A[] from the left and at the i-th step, we will increment the count of A[i] by 1 in O(logR) time. The number of elements smaller than A[i] is then the sum of occurrence counts of the range [0, A[i]-1] which can be queried in O(logR) time.</p><p>This is good enough if R is not too big. <strong>But if the range of numbers is large (say 1⁰⁹), this approach won’t work, </strong>since constructing the segment tree itself will take O(R) time.</p><p>Let’s use the coordinate compression trick here! <br>We will map each number in the original array to the range [0, N-1]. The i-th. smallest element is mapped to <em>i</em>. Since this is based on ranking, the relative ordering of elements doesn’t change and we can use these mapped values to compute our answer.</p><p>Now, we construct our segment tree and run our queries as before but this time the size of the Counts[] array is just N since our range is [0, N-1].</p><p>Effectively, this trick helped us to compress the numbers from a huge range into a smaller set which is more manageable. <br>This trick is even more powerful in two dimensions.</p><h3>Coordinate Compression In 2D</h3><h4>PROBLEM</h4><p>Consider a 2D array A[][] of size NxN where N ≤ 1⁰⁹. We have M(≤ 1⁰²) rectangular obstacles (non-intersecting) of size 1xK (horizontal) or Kx1(vertical). Each obstacle is given by a pair of starting (SR[i], SC[i]) and ending (ER[i], EC[i]) coordinates.<br>We need to determine the number of cells reachable from a given starting point (X, Y).</p><h4>NAIVE APPROACH</h4><p>This sounds very simple.<br>Construct a graph by treating each unblocked cell in the array as a node with edges to the neighboring cells and then run DFS from (X, Y) to check the number of reachable cells. <br>Pretty straightforward, right?</p><p><strong>Wrong! Notice the range of N.</strong> <br>The graph will have a size of 10¹⁸which is just not practical in terms of memory or time.</p><h4>MAIN IDEA</h4><p>Let’s apply coordinate compression here!<br>A few key observations are:</p><p>1. The number of obstacles M&lt;&lt;&lt; N therefore most of the grid is empty.</p><p>2. If groups of empty (unblocked) cells can be somehow merged into blocks, the resulting number of nodes in the graph would be much smaller.<br>For example, consider a subgrid of size 10x10 with unblocked cells. If any one of these cells is reachable then we can reach all the cells in the 10x10 block.</p><p>Thus, we want to compress groups of empty cells into blocks. See the figure below for a more visual intuition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*-M1zVa-JSlq4emlZ.png" /><figcaption>2D Coordinate Compression: Collapsing groups of cells into blocks. (References: <a href="https://stackoverflow.com/questions/29528934/coordinate-compression">https://stackoverflow.com/questions/29528934/coordinate-compression</a>)</figcaption></figure><h4>ALGORITHM</h4><p>Let’s see how to do this formally. <br>We want to divide the grid horizontally and vertically into blocks. We want to merge rows and columns that are similar to each other and can be treated as a single block.</p><p>For horizontal splitting, we will add a horizontal division at rows that are different from the row above it i.e. if an obstacle starts at that row or an obstacle ends at the row above it.<br>We can compute these indices by looking at the obstacle SR[] and ER[] coordinates. Let us store these row indices after sorting and de-duplication in R[]. By default, we will add the first row to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SscK8LlkhdO1e2ZFe298Ww.png" /><figcaption>Sketch of horizontal divisions added at rows where obstacles start or if an obstacle ends above it. The red blocks denote obstacles.</figcaption></figure><p>See the figure above. R[] will contain row indices 0 (first row), 2 (obstacle start), 3(obstacle ends in previous row), 5 (obstacle start), and 8 (obstacle ends in previous row).<br>Note that the i-th row block corresponds to a compressed version of R[i+1]-R[i] rows below it. For example, R0 corresponds to 2 rows and R5 corresponds to 3 rows.</p><p>Similarly, for vertical splitting, we will add a vertical division at columns that are different from the column on the left i.e. if an obstacle starts at that column or an obstacle ends at the column to the left of it.<br>Like before, we generate, sort, and de-duplicate these and store them in C[]. By default, we will add the first column to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEgLYEaal2sLnFr20fFFLw.png" /><figcaption>Sketch of vertical divisions added at columns where obstacles start or if an obstacle ends to the left of it. The red blocks denote obstacles.</figcaption></figure><p>See the figure above. C[] will contain column indices 0 (first column), 3(obstacle start), 6(obstacle start / obstacle ends in previous column), and 7(obstacle ends in previous column).<br>Note that the i-th column block corresponds to a compressed version of C[i+1]-C[i] columns to the right of it. For example, C0 corresponds to 3 columns and C7 corresponds to 2 columns.</p><p>We will now generate the compressed matrix which will have size |R| x |C|.<br>Imagine drawing both the vertical and horizontal divisions and treating each rectangular section generated as a block. See the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMNad7q2Uxy_Hi8YA7Wt8A.png" /><figcaption>Sketch of the compressed matrix composed of blocks (containing groups of cells from the original matrix). The red blocks denote obstacles. The yellow and blue blocks are non-obstacle cells colored alternatively for clarity.</figcaption></figure><p>We’ve compressed our original matrix of size 8 x 8 to a size of 5 x 4!</p><p>A few points to note here:<br>1. Each block will either have 0 obstacle cells or all obstacle cells because we have created divisions at the start and end of an obstacle. <br>2. The (i,j)-th block of the compressed matrix contains (R[i+1]-R[i])x(C[i+1]-C[i]) cells (treat R[|R|] and C[|C|] to be N. for the last division).</p><p>Note that since we only have M obstacles, |R|,|C| ≤ 2M and hence the size of the compressed matrix is just O(M²).</p><p>We can now run DFS on the compressed matrix by treating each non-obstacle block as a node (with edges to neighboring non-obstacle blocks). Since we know the obstacle positions it’s trivial enough to determine whether a block is composed of obstacle cells or not. <br>If a block is reachable, then that means all the cells to which the block corresponds to are reachable. Thus, we simply sum up the number of cells in all the reachable blocks and that’s our final answer.</p><p>The runtime can be computed as follows:</p><ul><li>O(MlogM) for computing R[] and C[]</li><li>O(MlogM) for identifying which block each obstacle cell belongs to</li><li>O(M²) for running DFS and computing the reachable blocks/cells</li></ul><p>Thus, the overall runtime is O(M²) as compared to O(N²) without coordinate compression.<br>By using coordinate compression, we were able to collapse the grid into a much smaller one and the runtime is now independent of N.</p><h3>Conclusion</h3><p>Coordinate compression is a useful trick that can be used to remove redundant information or collapse gaps effectively reducing the input size.</p><p>Do share your thoughts and feedback. Let me know if there are other problems you have come across where coordinate compression can be applied.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fff95326fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algorithms-digest/coordinate-compression-2fff95326fb">Coordinate Compression</a> was originally published in <a href="https://medium.com/algorithms-digest">Algorithms Digest</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>