<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by David De on Medium]]></title>
        <description><![CDATA[Stories by David De on Medium]]></description>
        <link>https://medium.com/@daviddecoding?source=rss-1c6e1f5644e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*J3IT_uZBVGZFMRVx39f3ZA.jpeg</url>
            <title>Stories by David De on Medium</title>
            <link>https://medium.com/@daviddecoding?source=rss-1c6e1f5644e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:14:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daviddecoding/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Vibe Coding vs. AI-Assisted Coding: Why the Difference Matters More Than You Think]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">As AI becomes a core part of how we build software, developers are splitting into two very different modes of working: Vibe Coding and&#x2026;</p><p class="medium-feed-link"><a href="https://daviddecoding.medium.com/vibe-coding-vs-ai-assisted-coding-why-the-difference-matters-more-than-you-think-070563b91bca?source=rss-1c6e1f5644e1------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://daviddecoding.medium.com/vibe-coding-vs-ai-assisted-coding-why-the-difference-matters-more-than-you-think-070563b91bca?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/070563b91bca</guid>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 09:03:55 GMT</pubDate>
            <atom:updated>2025-11-27T09:03:55.475Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Traits in you that help or hold you back]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Right now, there&#x2019;s an invisible operating system running in your brain that&#x2019;s deciding whether you&#x2019;ll tackle that difficult project or&#x2026;</p><p class="medium-feed-link"><a href="https://daviddecoding.medium.com/traits-in-you-that-help-or-hold-you-back-8c93eaee1e10?source=rss-1c6e1f5644e1------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://daviddecoding.medium.com/traits-in-you-that-help-or-hold-you-back-8c93eaee1e10?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c93eaee1e10</guid>
            <category><![CDATA[mindset]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 22:07:04 GMT</pubDate>
            <atom:updated>2025-11-02T22:07:04.672Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Manipulating Energy to create Matter]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">We know about how Matter and Energy are interchangeable. But does it hold meaning beyond just the physical nature of things?</p><p class="medium-feed-link"><a href="https://daviddecoding.medium.com/manipulating-energy-to-create-matter-97bb600eaa09?source=rss-1c6e1f5644e1------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://daviddecoding.medium.com/manipulating-energy-to-create-matter-97bb600eaa09?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/97bb600eaa09</guid>
            <category><![CDATA[spirituality]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 20:21:31 GMT</pubDate>
            <atom:updated>2025-03-10T20:21:31.112Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Leetcode Problems You Must Know]]></title>
            <link>https://daviddecoding.medium.com/leetcode-problems-you-must-know-429dfae5502d?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/429dfae5502d</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 00:24:03 GMT</pubDate>
            <atom:updated>2024-06-28T00:59:47.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BlEIXQklFRpMGHPwKne3uQ.png" /><figcaption>Crack FAANG Coding Interview — Image taken from Geek for Geeks</figcaption></figure><p>Are you looking for a set of DS&amp;A problems that would be a proxy for all the possible problems you might be asked at a Big Tech Interview?</p><p>Is there such a list of Problems? If so, then how do we use these problems?</p><p>…</p><p>What if I told you there is such a list of problems? A list that will train your brain to process DS&amp;A problems fast and will prepare it to absorb any other problem and its solutions like a sponge. Not only that, but it will also train your brain to come up with solutions to most problems.</p><p>Also, if you practice these problems every day till your interview, you will feel invisible.</p><p>…</p><p>I present to my readers,</p><p><strong>The Super Problems</strong>.</p><p>…</p><p>Here is how to use these:</p><ol><li>Start with each problem; of course, you will not be able to solve it initially. But learn the topics I have mentioned and do a few easy then mediums. After that, come back to the problem.</li><li>Then, once you can understand the solution to these problems, try to memorize them.</li><li>You might be thinking, “Memorize, that isn’t the right way to learn DS&amp;A.” To that, I would say, stop wasting your time on such BS notions and put your time into Memorizing these.</li><li>After a few weeks of constantly doing these problems, you should feel the power of DS&amp;A running through your veins.</li><li>Good luck!</li></ol><h3><a href="https://leetcode.com/problems/largest-rectangle-in-histogram/">84. Largest Rectangle in Histogram</a></h3><p>This is a strictly increasing max stack problem. As you iterate over the heights, you keep track of the heights in a strictly increasing stack. If the current height goes down compared to the last height seen, calculate the largest possible rectangle from the current index to the index stored with the height in the last element of the stack. Keep doing this till no element in the stack has a height bigger than the current height element. Then, update the index with the last greater height element found in the stack and add the current height with the index in the stack. At the end, till there are elements in the stack, calculate the possible area of the rectangles with the index and the total length of the heights array for each element in the stack.</p><pre>class Solution:<br>    def largestRectangleArea(self, heights: List[int]) -&gt; int:<br>        <br>        stk = []<br><br>        res = 0<br>        for idx, height in enumerate(heights):<br>            x = idx<br>            while stk and stk[-1][0] &gt; height:<br>                res = max(<br>                    res,<br>                    stk[-1][0] * (idx - stk[-1][1])<br>                )<br>                x = stk[-1][1]<br>                stk.pop()<br>            <br>            stk.append((height, x))<br>        <br>        while stk:<br>            res = max(<br>                res,<br>                stk[-1][0] * (len(heights) - stk[-1][1])<br>            )<br>            stk.pop()<br>        <br>        return res</pre><h3><a href="https://leetcode.com/problems/trapping-rain-water/">42. Trapping Rain Water</a></h3><p>This is a prefix sum problem. Calculate two prefix sum arrays where you store the maximum elements to the left and in the other, and you store the maximum elements to the right. Then, you take the minimum of the two maximums on the left and right and subtract the current height. If you get a positive value, that is, the amount of water that particular block will store above it. Keep adding them up.</p><pre>class Solution:<br>    def trap(self, height: List[int]) -&gt; int:<br>        <br>        max_left = [0 for _ in range(len(height))]<br>        max_right = [0 for _ in range(len(height))]<br><br>        for i in range(1, len(height)):<br>            max_left[i] = max(<br>                max_left[i - 1],<br>                height[i - 1]<br>            )<br>        <br>        for i in reversed(range(0, len(height) - 1)):<br>            max_right[i] = max(<br>                max_right[i + 1],<br>                height[i + 1]<br>            )<br>        <br>        res = 0<br>        for i in range(1, len(height)):<br>            val = min(max_left[i], max_right[i]) - height[i]<br>            if val &gt; 0:<br>                res += val<br>        <br>        return res</pre><h3><a href="https://leetcode.com/problems/reconstruct-itinerary/">332. Reconstruct Itinerary</a></h3><p>This is a backtracking while DFS problem. We start first by sorting the tickets. Then, we build an adjacent graph. We then start with “JFK,” and as we do a DFS, we keep removing the edges that we have already looked at; then, if we can get to a state where we have used up all the tickets, we can stop. Otherwise, we backtrack, put the edge back, move to the next edge, and keep traversing with DFS.</p><pre>class Solution:<br>    def findItinerary(self, tickets: List[List[str]]) -&gt; List[str]:<br>        graph = defaultdict(lambda: [])<br><br>        tickets.sort()<br><br>        for ticket in tickets:<br>            frm, to = ticket<br>            graph[frm].append(to)<br><br>        def dfs(node, res):<br>            if len(res) == len(tickets) + 1:<br>                return True<br><br>            temp = graph[node]<br>            for idx, neighbor in enumerate(temp):<br>                graph[node].pop(idx)<br>                res.append(neighbor)<br>                if dfs(neighbor, res):<br>                    return True<br>                res.pop()<br>                graph[node].insert(idx, neighbor)<br>            <br>            return False<br>        <br>        res = [&quot;JFK&quot;]<br>        dfs(&quot;JFK&quot;, res)<br><br>        return res</pre><h3><a href="https://leetcode.com/problems/the-skyline-problem/">218. The Skyline Problem</a></h3><p>This is a priority queue problem. We first create an array with the tuples (start/end, +/-height) where if we see a rising edge of a building, we put (-) height, and for a falling edge, we put (+) height. Then, we sort this array. After this we iterate through the array, and everytime we see a rising edge of a building (-height) we add the height in the priority queue, and when we run into a falling edge, we remove the height from the priority queue and heapify the priority queue. As we are doing this, we also check if the top height has changed in the priority queue; if it has, then we record the height and the start/end point in the result.</p><pre>class Solution:<br>    def getSkyline(self, buildings: List[List[int]]) -&gt; List[List[int]]:<br>        <br>        heights = []<br>        for building in buildings:<br>            start, end, height = building<br>            heights.append((start, -height))<br>            heights.append((end, height))<br>        <br>        heights.sort()<br><br>        pq, cur_height = [0], 0<br><br>        res = []<br>        for height in heights:<br>            x, y = height<br><br>            if y &lt; 0:<br>                heapq.heappush(pq, y)<br>            else:<br>                for idx, val in enumerate(pq):<br>                    if val == -y:<br>                        pq.pop(idx)<br>                        break<br>                heapq.heapify(pq)<br>            <br>            if cur_height != pq[0]:<br>                cur_height = pq[0]<br>                res.append((x, -cur_height))<br>        <br>        return res</pre><h3><a href="https://leetcode.com/problems/swim-in-rising-water/">778. Swim in Rising Water</a></h3><p>This is a BFS with a priority queue problem. We first start at (0, 0), and we will end the BFS traversal when we reach the bottom right cell. We will first calculate the maximum height of the current cell and the neighboring cells and add that with the neighboring cell into the priority queue as (max(current height, neighbor height), neighbor). Instead of a queue, we will use this priority queue to run our BFS, and the final height that we see in the top element of the priority queue when we have reached the bottom right cell is the answer.</p><pre>class Solution:<br>    def swimInWater(self, grid: List[List[int]]) -&gt; int:<br><br>        pq = [(grid[0][0], 0,0)]<br><br>        visited = set()<br>        res = 0<br>        while pq:<br>            height, x, y = heapq.heappop(pq)<br><br>            if x == len(grid) - 1 and y == len(grid[0]) - 1:<br>                return height<br>            <br>            if (x, y) in visited:<br>                continue<br>            visited.add((x, y))<br><br>            for x_d, y_d in [(0, -1), (0, 1), (-1, 0), (1, 0)]:<br>                n_x, n_y = x + x_d, y + y_d<br><br>                if n_x &gt;= 0 and n_x &lt; len(grid) and n_y &gt;= 0 and n_y &lt; len(grid[0]) and (n_x, n_y) not in visited:<br>                    heapq.heappush(pq, <br>                        (max(grid[n_x][n_y], height), n_x, n_y)<br>                    )<br>        <br>        return -1</pre><h3><a href="https://leetcode.com/problems/minimum-interval-to-include-each-query/">1851. Minimum Interval to Include Each Query</a></h3><p>Another priority queue problem, but also requires some greedy way of thinking like any other Interval problem.</p><pre>class Solution:<br>    def minInterval(self, intervals: List[List[int]], queries: List[int]) -&gt; List[int]:<br><br>        intervals.sort()<br><br>        queries = sorted([(val, idx) for idx, val in enumerate(queries)])<br><br>        pq = []<br>        i = 0<br><br>        res = [-1 for _ in range(len(queries))]<br>        for query in queries:<br>            val, idx = query<br><br>            while i &lt; len(intervals) and intervals[i][0] &lt;= val:<br>                heapq.heappush(pq, (intervals[i][1] - intervals[i][0] + 1, intervals[i][1]))<br>                i += 1<br>            <br>            while pq and pq[0][-1] &lt; val:<br>                heapq.heappop(pq)<br>            <br>            if pq:<br>                res[idx] = pq[0][0]<br>        <br>        return res<br><br><br><br>                <br><br></pre><h3><a href="https://leetcode.com/problems/lru-cache/">146. LRU Cache</a></h3><p>For this, you can use a hashtag and a doubly linked list. To simplify your life, you should use two dummy nodes to denote the beginning and end of the Doubly Linked List, which will help with all the edge cases.</p><pre>class Node:<br><br>    def __init__(self, key, value, next=None, prev=None):<br>        self.key = key<br>        self.value = value<br>        self.next = next<br>        self.prev = prev<br><br>class LRUCache:<br><br>    def __init__(self, capacity: int):<br>        self.cap = capacity<br><br>        self.start, self.end = Node(-1, -1), Node(-1, -1)<br>        self.start.next = self.end<br>        self.end.prev = self.start<br><br>        self.hashmap = {}<br><br>    def remove(self, node):<br>        prev = node.prev<br>        nxt = node.next<br><br>        prev.next = nxt<br>        nxt.prev = prev<br>    <br>    def insert(self, node):<br>        prev = self.end.prev<br>        nxt = self.end<br><br>        prev.next = node<br>        node.prev = prev<br><br>        nxt.prev = node<br>        node.next = nxt<br><br>    def get(self, key: int) -&gt; int:<br>        if key not in self.hashmap:<br>            return -1<br>        <br>        node = self.hashmap[key]<br>        self.remove(node)<br>        self.insert(node)<br><br>        return node.value<br><br>    def put(self, key: int, value: int) -&gt; None:<br>        if key in self.hashmap:<br>            node = self.hashmap[key]<br><br>            self.remove(node)<br><br>            node = Node(key, value)<br>            self.hashmap[key] = node<br>            self.insert(node)<br><br>            return<br>        <br>        if len(self.hashmap) == self.cap:<br>            node = self.start.next<br>            self.remove(node)<br>            del self.hashmap[node.key]<br>        <br>        node = Node(key, value)<br>        self.hashmap[key] = node<br>        self.insert(node)<br><br># Your LRUCache object will be instantiated and called as such:<br># obj = LRUCache(capacity)<br># param_1 = obj.get(key)<br># obj.put(key,value)</pre><h3><a href="https://leetcode.com/problems/reverse-pairs/">493. Reverse Pairs</a></h3><p>This requires a strong knowledge of merge sort. After each array breakup, you count the number of pairs just before merging.</p><pre>class Solution:<br><br>    def merge(self, arr, low, mid, high):<br>        temp = []  # temporary array<br>        left = low  # starting index of left half of arr<br>        right = mid + 1  # starting index of right half of arr<br><br>        # storing elements in the temporary array in a sorted manner<br>        while left &lt;= mid and right &lt;= high:<br>            if arr[left] &lt;= arr[right]:<br>                temp.append(arr[left])<br>                left += 1<br>            else:<br>                temp.append(arr[right])<br>                right += 1<br><br>        # if elements on the left half are still left<br>        while left &lt;= mid:<br>            temp.append(arr[left])<br>            left += 1<br><br>        # if elements on the right half are still left<br>        while right &lt;= high:<br>            temp.append(arr[right])<br>            right += 1<br><br>        # transferring all elements from temporary to arr<br>        for i in range(low, high + 1):<br>            arr[i] = temp[i - low]<br><br>    def countPairs(self, arr, low, mid, high):<br>        right = mid + 1<br>        cnt = 0<br>        for left in range(low, mid + 1):<br>            while right &lt;= high and arr[left] &gt; 2 * arr[right]:<br>                right += 1<br>            cnt += (right - (mid + 1))<br>        return cnt<br><br>    def mergeSort(self, arr, low, high):<br>        if low &gt;= high:<br>            return 0<br>        <br>        cnt = 0<br>        mid = (low + high) // 2<br>        cnt += self.mergeSort(arr, low, mid)<br>        cnt += self.mergeSort(arr, mid + 1, high)<br>        cnt += self.countPairs(arr, low, mid, high)<br>        self.merge(arr, low, mid, high)<br><br>        return cnt<br><br>    def reversePairs(self, nums: List[int]) -&gt; int:<br>        return self.mergeSort(nums, 0, len(nums) - 1)</pre><h3><a href="https://leetcode.com/problems/regular-expression-matching/">10. Regular Expression Matching</a></h3><p>This is a dynamic programming problem that requires a good understanding of how to break it into smaller recursive steps.</p><pre>class Solution:<br>    def isMatch(self, s: str, p: str) -&gt; bool:<br>        <br>        def dfs(i, j, cache):<br>            if (i, j) in cache:<br>                return cache[(i, j)]<br><br>            if i &gt;= len(s) and j &gt;= len(p):<br>                return True<br>            <br>            if j &gt;= len(p):<br>                return False<br>            <br>            match = i &lt; len(s) and (s[i] == p[j] or p[j] == &quot;.&quot;)<br>            if j + 1 &lt; len(p) and p[j + 1] == &quot;*&quot;:<br>                cache[(i, j)] = dfs(i, j + 2, cache) or (match and dfs(i + 1, j, cache))<br>                return cache[(i, j)]<br>            <br>            if match:<br>                cache[(i, j)] = dfs(i + 1, j + 1, cache)<br>                return cache[(i, j)]<br>            <br>            cache[(i, j)] = False<br>            return cache[(i, j)]<br>        <br>        return dfs(0, 0, {})</pre><h3>Few Bonus Problems</h3><h3><a href="https://leetcode.com/problems/4sum/">18. 4Sum</a></h3><p>This can be solved by sorting the array. Then, there are 2 for loops, with a two-pointer at the next element of the 2nd for loop to the end of the array.</p><pre>class Solution:<br>    def fourSum(self, nums: List[int], target: int) -&gt; List[List[int]]:<br>        <br>        nums.sort()<br><br>        res = []<br>        for i in range(len(nums)):<br>            if i &gt; 0 and nums[i] == nums[i - 1]:<br>                continue<br>            for j in range(i+1, len(nums)):<br>                if j != (i + 1) and nums[j] == nums[j - 1]:<br>                    continue<br>                k, l = j + 1, len(nums) - 1<br><br>                while k &lt; l:<br>                    val = nums[i] + nums[j] + nums[k] + nums[l]<br>                    if val == target:<br>                        res.append([nums[i], nums[j], nums[k], nums[l]])<br>                        k += 1<br>                        l -= 1<br>                        while k &lt; l and nums[k] == nums[k - 1]:<br>                            k += 1<br>                        while k &lt; l and nums[l] == nums[l + 1]:<br>                            l -= 1<br>                    elif val &gt; target:<br>                        l -= 1<br>                    else:<br>                        k += 1<br>        <br>        return res</pre><h3><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">121. Best Time to Buy and Sell Stock</a></h3><p>This is a two-pointer/sliding window problem. Take the two pointers as the first and second element of the prices array, and till the second pointer hits the end of the array, keep iterating. As you iterate, see if the price at the second pointer is below the element at the first pointer. In that case, you have found a lower value to buy the stock, so update the first pointer to be the second. For each first and second pointer pair, calculate the profit. Take the maximum of these profits.</p><pre>class Solution:<br>    def maxProfit(self, prices: List[int]) -&gt; int:<br>        i, j = 0, 1<br><br>        res = 0<br>        while j &lt; len(prices):<br>            while prices[j] &lt; prices[i]:<br>                i += 1<br>            <br>            res = max(<br>                res,<br>                prices[j] - prices[i]<br>            )<br>            j += 1<br>        <br>        return res</pre><h3>More things you might be interested in</h3><h4>Coding Interview</h4><ul><li><a href="https://daviddecoding.medium.com/must-know-coding-and-problem-solving-concepts-to-ace-your-big-tech-interview-2f8745decd58"><strong>Must Know Coding and Problem — Solving Concepts to Ace Your Big Tech Interview</strong></a></li></ul><h4>System Design</h4><ul><li><a href="https://daviddecoding.medium.com/system-design-coding-it-up-f085a898a110"><strong>Big Tech Interview: Implementations of Alex Xu’s System Design Algorithms (Python) — Part 1</strong></a></li><li><a href="https://daviddecoding.medium.com/know-your-bits-and-bytes-406942418c05">Know your Bits and Bytes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=429dfae5502d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcoding in Assembly — Challenge Accepted]]></title>
            <link>https://daviddecoding.medium.com/leetcoding-in-assembly-challenge-accepted-73698bfc4a74?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/73698bfc4a74</guid>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 17:18:37 GMT</pubDate>
            <atom:updated>2024-04-24T17:29:08.114Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcoding in Assembly — Challenge Accepted</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*SLkUU3gD2XSAXF1FLWw_bA.png" /><figcaption>Assembly Language Icon. Found at <a href="https://thenounproject.com/icon/asm-762420/">https://thenounproject.com/icon/asm-762420/</a></figcaption></figure><p>I saw this video on Youtube the other day, where Low Level Learning used Assembly to solve a Leetcode problem. I decided to take the challenge up to solve at-least 10 leetcode problems using Assembly.</p><p>First of all, as he says in the video there is no Assembly option in Leetcode, so we need to improvise. I will do what he basically did, that is use <a href="https://gcc.gnu.org/onlinedocs/gcc/extensions-to-the-c-language-family/how-to-use-inline-assembly-language-in-c-code.html">Inline Assembly in C</a>.</p><p>Also, I will not be using Intel Syntax, instead I am more comfortable using the AT&amp;T version so I will do that.</p><p>The other thing that I will also change is, I will use <a href="https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html">Extended Assembly</a> instead of Assembly.</p><p>Here are the 10 problems, these from the Array, Strings, Dynamic Programming problems.</p><h3><a href="https://leetcode.com/problems/defanging-an-ip-address/">1108. Defanging an IP Address</a></h3><pre>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;<br><br>char * defangIPaddr(char * address){<br>    int len_of_orig = strlen(address);<br>    <br>    int len_of_new = strlen(address) + 7;<br>    char* res = malloc(sizeof(char) * len_of_new);<br>    res[len_of_new - 1] = &#39;\0&#39;;<br>    <br>    __asm__ __volatile__ (<br>        &quot;xor %%rcx, %%rcx;&quot;<br>        &quot;xor %%rdx, %%rdx;&quot;<br>        &quot;xor %%r9, %%r9;&quot;<br><br>        &quot;mov $0, %%rcx;&quot; // i the index for address<br>        &quot;mov $0, %%rdx;&quot; // j the index for res<br><br>    &quot;loop%=:;&quot;<br>        &quot;cmpl %1, %%ecx;&quot;<br>        &quot;je end%=;&quot;<br>        <br>        &quot;movb (%2, %%rcx, 1), %%r9b;&quot;<br>        &quot;cmpb $46,  %%r9b;&quot;<br>        &quot;je is_dot%=;&quot;<br>        <br>        &quot;movb %%r9b, (%0, %%rdx, 1);&quot;<br>        &quot;inc %%rdx;&quot;<br>        <br>        &quot;jmp continue_loop%=;&quot;<br><br>    &quot;continue_loop%=:;&quot;<br>        &quot;inc %%rcx;&quot;<br>        &quot;jmp loop%=;&quot;<br>    <br>    &quot;is_dot%=:;&quot;<br>        &quot;movb $91, (%0, %%rdx, 1);&quot;<br>        &quot;inc %%rdx;&quot;<br>        &quot;movb $46, (%0, %%rdx, 1);&quot;<br>        &quot;inc %%rdx;&quot;<br>        &quot;movb $93, (%0, %%rdx, 1);&quot;<br>        &quot;inc %%rdx;&quot;<br><br>        &quot;jmp continue_loop%=;&quot;<br>    <br>    &quot;end%=:;&quot;<br>        : &quot;+r&quot; (res) <br>        : &quot;r&quot; (len_of_orig), &quot;r&quot; (address)<br>    );<br><br><br><br>    return res;<br>}</pre><h3><a href="https://leetcode.com/problems/n-th-tribonacci-number/">1137. N-th Tribonacci Number</a></h3><pre>int tribonacci(int n){<br>    int res = 0;<br><br>    __asm__ __volatile__ (<br>        &quot;cmpl $0, %1;&quot;<br>        &quot;je end_early_0%=;&quot;<br><br>        &quot;cmp $1, %1;&quot;<br>        &quot;je end_early_1%=;&quot;<br><br>        &quot;movl $0, %%eax;&quot;<br>        &quot;movl $1, %%ecx;&quot;<br>        &quot;movl $1, %%edx;&quot;<br><br>        &quot;movl $2, %%r8d;&quot;<br><br>    &quot;loop%=:;&quot;<br>        &quot;cmpl %%r8d, %1;&quot;<br>        &quot;je end%=;&quot;<br><br>        &quot;movl $0, %%r9d;&quot;<br><br>        &quot;addl %%eax, %%r9d;&quot;<br>        &quot;addl %%ecx, %%r9d;&quot;<br>        &quot;addl %%edx, %%r9d;&quot;<br><br>        &quot;movl %%ecx, %%eax;&quot;<br>        &quot;movl %%edx, %%ecx;&quot;<br>        &quot;movl %%r9d, %%edx;&quot;<br><br>        &quot;incl %%r8d;&quot;<br>        &quot;jmp loop%=;&quot;<br><br>    &quot;end%=:;&quot;<br>        &quot;movl %%edx, %0;&quot;<br>        &quot;jmp last%=;&quot;<br>    <br>    &quot;end_early_0%=:;&quot;<br>        &quot;movl $0, %0;&quot;<br>        &quot;jmp last%=;&quot;<br>    <br>    &quot;end_early_1%=:;&quot;<br>        &quot;movl $1, %0;&quot;<br>        &quot;jmp last%=;&quot;<br><br>    &quot;last%=:&quot;<br>        : &quot;+r&quot; (res)<br>        : &quot;r&quot; (n)<br>    );<br><br>    return res;<br>}</pre><h3><a href="https://leetcode.com/problems/jewels-and-stones/">771. Jewels and Stones</a></h3><pre>#include &lt;string.h&gt;<br><br>int numJewelsInStones(char* jewels, char* stones) {<br>    int res = -0;<br><br>    int len_of_jewels = strlen(jewels);<br>    int len_of_stones = strlen(stones);<br><br>    __asm__ __volatile__ (<br>        &quot;xor %%rax, %%rax;&quot;<br><br>        &quot;xor %%rcx, %%rcx;&quot;<br>        &quot;xor %%rdx, %%rdx;&quot;<br><br>        &quot;xor %%r9, %%r9;&quot;<br>        &quot;xor %%r10, %%r10;&quot;<br><br>    &quot;loop_i%=:;&quot;<br>        &quot;cmpl %%ecx, %1;&quot;<br>        &quot;je end_loop_i%=;&quot;<br><br>        &quot;movb (%2, %%rcx, 1), %%r9b;&quot;<br>        &quot;inc %%rcx;&quot;<br><br>        &quot;loop_j%=:;&quot;<br>            &quot;cmpl %%edx, %3;&quot;<br>            &quot;je end_loop_j%=;&quot;<br><br>            &quot;movb (%4, %%rdx, 1), %%r10b;&quot;<br>            &quot;inc %%rdx;&quot;<br><br>            &quot;cmpb %%r9b, %%r10b;&quot;<br>            &quot;je add_to_result%=;&quot;<br><br>            &quot;jmp loop_j%=;&quot;<br><br>        &quot;add_to_result%=:;&quot;<br>            &quot;incl %%eax;&quot;<br>            &quot;jmp loop_j%=;&quot;<br>        <br>        &quot;end_loop_j%=:;&quot;<br>            &quot;movl $0, %%edx;&quot;<br>            &quot;jmp loop_i%=;&quot;<br>    <br>    &quot;end_loop_i%=:;&quot;<br>        &quot;movl %%eax, %0;&quot;<br>    : &quot;+r&quot; (res)<br>    : &quot;r&quot; (len_of_jewels), &quot;r&quot; (jewels), &quot;r&quot; (len_of_stones), &quot;r&quot; (stones)<br>    );<br><br>    return res;<br>}</pre><h3><a href="https://leetcode.com/problems/climbing-stairs/">70. Climbing Stairs</a></h3><pre><br>__attribute__((naked))<br>int climbStairs(int n) {<br>    __asm__(<br>        &quot;movl $1, %eax;&quot; // pre_pre = 1<br>        &quot;movl $1, %ecx;&quot; // pre = 1<br>        &quot;movl $2, %edx;&quot; // res = 2<br><br>    &quot;loop:;&quot; // while res &gt; n<br>        &quot;cmpl %edi, %edx;&quot;<br>        &quot;jg end;&quot;<br><br>        &quot;movl %eax, %esi;&quot; // tmp = pre_pre<br>        &quot;addl %ecx, %esi;&quot; // tmp += pre<br>        &quot;movl %eax, %ecx;&quot; // pre_pre = pre<br>        &quot;movl %esi, %eax;&quot; // pre = tmp<br><br>        &quot;incl %edx;&quot;<br>        &quot;jmp loop;&quot;<br>    <br>    &quot;end:;&quot;<br>        &quot;ret;&quot;<br>    );<br>}</pre><h3><a href="https://leetcode.com/problems/fibonacci-number/">509. Fibonacci Number</a></h3><pre><br>__attribute__((naked))<br>int fib(int n){<br>    __asm__(<br>        &quot;cmpl $0, %edi;&quot; // if EDI == 0 {<br>        &quot;je end_immediate;&quot;<br><br>        &quot;movl $0, %ecx;&quot; // ECX = 0; pre<br>        &quot;movl $1, %eax;&quot; // EAX = 1; Res<br>        &quot;movl $2, %edx;&quot; // EDX = 2; n<br><br>    &quot;loop:;&quot;<br>        &quot;cmpl %edi, %edx;&quot; // EDI = n<br>        &quot;jg end;&quot; // while ebx &lt;= edi {<br>        <br>        &quot;movl %eax, %esi;&quot; // ESI = EAX; temp<br>        &quot;addl %ecx, %esi;&quot; // ESI += ECX; temp<br>        &quot;movl %eax, %ecx;&quot; // ECX = EAX; pre<br>        &quot;movl %esi, %eax;&quot; // EAX = ESI; res<br><br>        &quot;incl %edx;&quot;<br>        &quot;jmp loop;&quot;<br>    &quot;end:;&quot;<br>        &quot;ret;&quot;<br>    &quot;end_immediate:;&quot;<br>        &quot;movl $0, %eax;&quot; // EAX = 0; res<br>        &quot;ret;&quot;<br>    );<br>}</pre><h3><a href="https://leetcode.com/problems/shuffle-the-array/">1470. Shuffle the Array</a></h3><pre><br><br>/**<br> * Note: The returned array must be malloced, assume caller calls free().<br> */<br>int* shuffle(int* nums, int numsSize, int n, int* returnSize){<br>    int* res = malloc(sizeof(int) * numsSize);<br><br>    __asm__ __volatile__(<br>        <br>        &quot;movl $0, %%r8d;&quot;<br>        &quot;movl %%edx, %%r9d;&quot;<br>        &quot;mov $0, %%r10;&quot;<br><br>    &quot;loop_i%=:;&quot;<br>        &quot;cmpl %%edx, %%r8d;&quot;<br>        &quot;je end_loop_i%=;&quot;<br><br>        &quot;movl (%%rcx, %%r8, 4), %%esi;&quot;<br>        &quot;movl %%esi, (%%rax, %%r10, 4);&quot;<br>        &quot;inc %%r10;&quot;<br><br>        &quot;movl (%%rcx, %%r9, 4), %%esi;&quot;<br>        &quot;movl %%esi, (%%rax, %%r10, 4);&quot;<br>        &quot;inc %%r10;&quot;<br><br>        &quot;inc %%r8d;&quot;<br>        &quot;inc %%r9d;&quot;<br>        &quot;jmp loop_i%=;&quot;<br><br>    &quot;end_loop_i%=:;&quot;<br>    : &quot;=a&quot; (res)<br>    : &quot;a&quot; (res), &quot;c&quot; (nums), &quot;d&quot; (n)<br>    : &quot;r8&quot;, &quot;r9&quot;, &quot;r10&quot;, &quot;memory&quot;<br>    );<br><br>    *returnSize = numsSize;<br>    return res;<br>}</pre><h3><a href="https://leetcode.com/problems/number-of-employees-who-met-the-target/">2798. Number of Employees Who Met the Target</a></h3><pre>int numberOfEmployeesWhoMetTarget(int* hours, int hoursSize, int target){<br>    int res = 0;<br><br>    __asm__ __volatile__ (<br>        &quot;mov $0, %%r8d;&quot;<br>        &quot;movl $0, %%eax;&quot;<br><br>    &quot;loop%=:;&quot;<br>        &quot;cmpl %%r8d, %2;&quot;<br>        &quot;je end%=;&quot;<br><br>        &quot;movl (%1, %%r8, 4), %%r9d;&quot;<br>        &quot;inc %%r8;&quot;<br><br>        &quot;cmpl %3, %%r9d;&quot;<br>        &quot;jge accumulate%=;&quot;<br><br>        &quot;jmp loop%=;&quot;<br><br>    &quot;accumulate%=:;&quot;<br>        &quot;incl %%eax;&quot;<br>        &quot;jmp loop%=;&quot;<br><br>    &quot;end%=:;&quot;<br>        &quot;movl %%eax, %0;&quot;<br>        : &quot;=r&quot; (res)<br>        : &quot;r&quot; (hours), &quot;r&quot; (hoursSize), &quot;r&quot; (target)<br>        : &quot;r8&quot;, &quot;r9&quot;, &quot;memory&quot;, &quot;eax&quot;<br>    );<br><br>    return res;<br>}</pre><h3><a href="https://leetcode.com/problems/score-of-a-string/">3110. Score of a String</a></h3><pre>int scoreOfString(char* s) {<br>    int res = 0;<br><br>    __asm__ __volatile__(<br>        &quot;mov $0, %%rax;&quot;<br><br>        &quot;mov %%rcx, %%r8;&quot;<br>        &quot;mov $0, %%r11;&quot;<br>    <br>    &quot;loop%=:;&quot;<br>        &quot;movb 1(%%r8), %%r9b;&quot;<br><br>        &quot;cmpb $0, %%r9b;&quot;<br>        &quot;je end%=;&quot;<br><br>        &quot;movb (%%r8), %%r10b;&quot;<br><br>        &quot;subb $97, %%r9b;&quot;<br>        &quot;subb $97, %%r10b;&quot;<br><br>        &quot;cmpb %%r10b, %%r9b;&quot;<br>        &quot;jg go_to_10_g_9%=;&quot;<br><br>        &quot;subl %%r9d, %%r10d;&quot;<br><br>        &quot;addl %%r10d, %%r11d;&quot;<br><br>        &quot;inc %%r8;&quot;<br>        &quot;jmp loop%=;&quot;<br><br>    &quot;go_to_10_g_9%=:;&quot;<br>        <br>        &quot;subl %%r10d, %%r9d;&quot;<br><br>        &quot;addl %%r9d, %%r11d;&quot;<br><br>        &quot;inc %%r8;&quot;<br>        &quot;jmp loop%=;&quot;<br>    <br>    &quot;end%=:;&quot;<br>        &quot;movl %%r11d, %%eax;&quot;<br>        : &quot;+a&quot; (res)<br>        : &quot;c&quot; (s)<br>        : &quot;r8&quot;, &quot;r9&quot;, &quot;r10&quot;, &quot;r11&quot;, &quot;memory&quot;<br>    );<br><br>    return res;<br>}</pre><h3><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">121. Best Time to Buy and Sell Stock</a></h3><pre><br><br>int maxProfit(int* prices, int pricesSize) {<br>    int res = 0;<br><br>    __asm__ __volatile__(<br>        &quot;mov $0, %%r8;&quot;<br><br>        &quot;mov (%%rcx), %%r10d;&quot;<br>        &quot;mov $0, %%r11;&quot;<br><br>    &quot;loop_i%=:;&quot;<br>        &quot;cmpl %%edx, %%r8d;&quot;<br>        &quot;je end%=;&quot;<br><br>        &quot;movl (%%rcx, %%r8, 4), %%esi;&quot;<br>        &quot;inc %%r8;&quot;<br><br>        &quot;cmpl %%r10d,  %%esi;&quot;<br>        &quot;jl min_price_so_far%=;&quot;<br>    <br>    &quot;max_profit_so_far%=:;&quot;<br>        &quot;subl %%r10d, %%esi;&quot;<br>        &quot;cmpl %%r11d, %%esi;&quot;<br>        &quot;jg note_max%=;&quot;<br><br>        &quot;jmp loop_i%=;&quot;<br><br>    &quot;min_price_so_far%=:;&quot;<br>        &quot;movl %%esi, %%r10d;&quot;<br>        &quot;jmp max_profit_so_far%=;&quot;<br>        <br>    &quot;note_max%=:;&quot;<br>        &quot;movl %%esi, %%r11d;&quot;<br>        &quot;jmp loop_i%=;&quot;<br><br><br>    &quot;end%=:;&quot;<br>        &quot;movl %%r11d, %%eax;&quot;<br>        : &quot;=a&quot; (res)<br>        : &quot;c&quot; (prices), &quot;d&quot; (pricesSize)<br>        : &quot;r8&quot;, &quot;r9&quot;, &quot;r10&quot;, &quot;r11&quot;, &quot;esi&quot;, &quot;edi&quot;, &quot;memory&quot;<br>    ); <br><br>    return res;<br>}</pre><h3><a href="https://leetcode.com/problems/concatenation-of-array/">1929. Concatenation of Array</a></h3><pre>/**<br> * Note: The returned array must be malloced, assume caller calls free().<br> */<br>int* getConcatenation(int* nums, int numsSize, int* returnSize) {<br>    int* res = malloc(sizeof(int) * 2 * numsSize);<br><br>    __asm__ __volatile__ (<br>        &quot;mov $0, %%r8;&quot;<br>        &quot;mov $0, %%r9;&quot;<br>        &quot;movl %%edx, %%r10d;&quot;<br><br>    &quot;loop%=:;&quot;<br>        &quot;cmpl %%r8d, %%edx;&quot;<br>        &quot;je end_loop_first%=;&quot;<br><br>        &quot;movl (%%rcx, %%r8, 4), %%r11d;&quot;<br>        &quot;inc %%r8;&quot;<br><br>        &quot;movl %%r11d, (%%rax, %%r9, 4);&quot;<br>        &quot;inc %%r9;&quot;<br><br>        &quot;movl %%r11d, (%%rax, %%r10, 4);&quot;<br>        &quot;inc %%r10;&quot;<br><br>        &quot;jmp loop%=;&quot;<br><br>    &quot;end_loop_first%=:;&quot;<br>        : &quot;+a&quot; (res)<br>        : &quot;c&quot; (nums), &quot;d&quot; (numsSize)<br>        : &quot;r8&quot;, &quot;r9&quot;, &quot;r10&quot;, &quot;r11&quot;<br>    );<br><br>    *returnSize = 2 * numsSize;<br>    return res;<br>}</pre><h3>Conclusion</h3><p>Leetcode is a great place to hone your programming skills in almost any programming language possible. If you want to see the video from Low Level Learning, here you go:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlALPErFlfNQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlALPErFlfNQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlALPErFlfNQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8471e65fc9d5b1455bc278c4620b0bc5/href">https://medium.com/media/8471e65fc9d5b1455bc278c4620b0bc5/href</a></iframe><h3>More things you might be interested in</h3><h3>Leetcoding in Rust</h3><ul><li><a href="https://medium.com/@daviddecoding/leetcoding-in-rust-curious-case-of-sub-arrays-and-its-relationship-with-k-5c642461d79f"><strong>Curious case of Sub Arrays and its relationship with K</strong></a></li><li><a href="https://medium.com/@daviddecoding/leetcoding-in-rust-making-monotonic-stack-and-queue-easy-72105eee9970">Making Monotonic Stack and Queue Easy</a></li></ul><h3>Coding</h3><ul><li><a href="https://medium.com/@daviddecoding/must-know-coding-and-problem-solving-concepts-to-ace-your-big-tech-interview-2f8745decd58"><strong>Must Know Coding and Problem-Solving Concepts to Ace Your Big Tech Interview</strong></a></li></ul><h3>System Design</h3><ul><li><a href="https://daviddecoding.medium.com/system-design-coding-it-up-f085a898a110"><strong>Big Tech Interview: Implementations of Alex Xu’s System Design Algorithms (Python) — Part 1</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73698bfc4a74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Know your Bits and Bytes]]></title>
            <link>https://daviddecoding.medium.com/know-your-bits-and-bytes-406942418c05?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/406942418c05</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 17:36:58 GMT</pubDate>
            <atom:updated>2024-03-18T11:09:41.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Just 1s and 0s" src="https://cdn-images-1.medium.com/max/960/1*iVDpbU4mALu6xdWMHEdQKA.jpeg" /><figcaption>Pic from <a href="https://creazilla.com/nodes/1643906-byte-bits-computer-illustration">https://creazilla.com/nodes/1643906-byte-bits-computer-illustration</a></figcaption></figure><h3>Bits, Nibbles, Bytes</h3><h4>Bit</h4><p><strong>Bits is a single 0 or 1.</strong> But this is not very meaningful; what would be more useful are numbers and characters that can be used to calculate things or print them on the screen.</p><h4>Nibble</h4><p><strong>Nibble is a series of 4 bits, e.g., 0110, 1111. </strong>This is more meaningful as we can store 4 bits of information, which can be the decimal numbers <strong>6 (0110 in Binary) </strong>and<strong> 15 (1111 in Binary).</strong></p><h4>Byte</h4><p><strong>Byte is a series of 8 bits, or 2 Nibble, e.g., 0110 0110, 1111 1111.</strong> This is what most computers use today, as a single unit of information. The most important reason for choosing 8 bits, instead of anything else, is that it can be represented as 2^power. So the above 2 bytes can represent the decimal numbers <strong>102 (0110 0110 in Binary)</strong> and <strong>255 (1111 1111 in Binary)</strong>.</p><h3>Word, DWord, QWord</h3><h4>Word</h4><p><strong>1 Word is a series of 2 Bytes. </strong>Most computers today are 16-bit, 32-bit, and 64-bit, not 8-bit. So we need to call this something too. So, 2 Bytes or 16 bit is called Word.</p><h4>DWord</h4><p><strong>1 Double Word/DWord is a series of 4 Bytes.</strong> For 32-bit addressing or numbers, we use DWord.</p><h4>QWord</h4><p><strong>1 Quad Word/QWord is a series of 8 Bytes.</strong> For 64-bit addressing or numbers, we use QWord.</p><h3>Kilo Bytes, Mega Bytes, Giga Bytes, Tera Bytes and Peta Bytes</h3><p>Now, of course, the size of things is no longer just how many bits our CPU can handle but how big a piece of information like a number, text, image, or video is.</p><h4>Kilo Bytes/KB</h4><p><strong>1 KB = 1024 B = 2 X 10¹⁰ b (Bits)</strong></p><h4>Mega Bytes/MB</h4><p><strong>1 MB = 1024 X 1024 B = 2 X 10²⁰ b (Bits)</strong></p><h4>Giga Bytes/GB</h4><p><strong>1 GB = 1024 X 1024 X 1024 B = 2 X 10³⁰ b (Bits)</strong></p><h4>Tera Bytes/TB</h4><p><strong>1 TB = 1024 X 1024 X 1024 X 1024 B = 2 X 10⁴⁰ b (Bits)</strong></p><h4>Peta Bytes/PB</h4><p><strong>1 PB = 1024 X 1024 X 1024 X 1024 X 1024 B = 2 X 10⁵⁰ b (Bits)</strong></p><h3>Bytes and Hexadecimal Numbers</h3><h4>Hexadecimal Numbers</h4><p>Binary has two numbers, <strong>0</strong> and <strong>1</strong>. Decimal, as the name implies, has tens numbers: <strong>0, 1, 2, 3, 4, 5, 6, 7, 8,</strong> and <strong>9</strong>. Similarly, Hexadecimal has sixteen numbers: <strong>0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e,</strong> and <strong>f</strong>.</p><p>So, as an example, 1f is a Hexadecimal number which can be converted to Decimal as we convert Binary to Decimal:</p><p><strong>1f</strong> = <strong><em>1</em></strong><em> X 16</em><strong><em>¹</em> + <em>f</em></strong><em> X 16</em><strong><em>⁰</em></strong> = <em>16</em> + <em>15</em> = <strong><em>31</em></strong></p><p>Observe f = 15, so we can deduce a = 10, b = 11, …, f = 15 in Hexadecimal.</p><h4>Bytes and Hexadecimal Numbers</h4><p>But what is so special about Hexadecimal Numbers? Well, this perfectly fits into the way Bytes are represented. So, let&#39;s take the two examples above.</p><p><strong>0110 0110</strong></p><p>This can be represented in Hexadecimal as just 0x<strong>66</strong>.</p><p><strong>1111 1111</strong></p><p>Similarly, this can be represented in Hexadecimal as just 0x<strong>ff</strong>.</p><blockquote><strong>Note: <em>We put ‘0x’ as the prefix of all Hexadecimal numbers.</em></strong></blockquote><p>You must have seen addresses represented in 32-bit (4 B) machines as <strong>0x12ff3410</strong>. This is in hex and can be broken up into bits as:</p><p><strong>0001 0010 1111 1111 0011 0100 0001 0000</strong></p><p>Which do you like better? I like the hex version of the same 4 Bytes much better than the binary version.</p><h3>Signed Integer 16b (2B), 32b (4B), 64b (8B)</h3><p>Finally, we can start representing numbers. The first type of Numbers we generally deal with are called Integers. These can be Signed or Unsigned. Signed as Integers, which can be positive or negative, e.g., -1, 10, -999, etc.</p><p>We generally represent them as 16-bit, 32-bit, or 64-bit, which can also be defined as 2 Bytes, 4 Bytes, or 64 Bytes.</p><p>We generally take the Rightmost Bit (Most Significant Digit) to represent the Sign, so we are left with numbers 16–1=15 bits for 16-bit, 32–1=31 bits for 32-bit, or 64–1=63 bits for 64-bit Integers, respectively.</p><h4>Negative Integers (Twos Complement)</h4><p>I just mentioned that Negative Integers uses the Rightmost Bit (Most Significant Digit) to represent its a Negative Integer, but I am not being fully correct. Rather Negative Integer are represented as Integers with which if you add the Positive version of Integer will result into 0.</p><p>So the -6 will be represented as an Integer that when added to +6 will result into a 0. So how does that work?</p><p>Lets take 6, and convert it into a 16-bit (2 Bytes) Integer: <strong>0000 0000 0000 0110.</strong></p><ol><li>Then, we have to turn into its Complement (1s Complement): <br><strong>1111 1111 1111 1001</strong>. <br>What this means is that all the bits that were 0, were flipped to 1, and all the bits that were 1 previously, were flipped to 0.</li><li>Then, we add 1 to this new number (2s Complement): <br> 1111 1111 1111 1001 + 0000 0000 0000 0001 <br>= <strong>1111 1111 1111 1010.</strong></li></ol><p>This is how we represent -6: <strong>1111 1111 1111 1010.</strong></p><p>And to show you that I didn’t lie when I said, +6 + (-6) is actually equal to 0. Lets add these Binary numbers together:</p><pre>Adding the +6 + (-6):<br> <br>  0000 0000 0000 0110<br>+ 1111 1111 1111 1010<br>- - - - - - - - - - - <br>1 0000 0000 0000 0000</pre><p>But we do get a 1 at the Rightmost position don’t we? Yes, but it gets dropped as it doesn’t fit in a 16-bit Integer. So, the final result indeed is going to be 0 or in hex: 0x0000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*2K9BdxWUJisPfVBFt9WB0g.png" /><figcaption>Taken from <a href="https://towardsdatascience.com/unsinged-signed-integers-and-casting-in-rust-9a847bfc398f">https://towardsdatascience.com/unsinged-signed-integers-and-casting-in-rust-9a847bfc398f</a></figcaption></figure><h3>Unsigned Integer 16b (2B), 32b (4Bytes), 64b (8B)</h3><p>The other kind of Integers are Unsigned Integers. In this case, we don’t need the Rightmost Bit, as all numbers are Positive. So, we can use the complete set of bits to represent an Integer. This type of Integer is generally used to store the size of an element or something similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*9IjacuqrqnWAFMXaedsemQ.png" /><figcaption>Taken from <a href="https://towardsdatascience.com/unsinged-signed-integers-and-casting-in-rust-9a847bfc398f">https://towardsdatascience.com/unsinged-signed-integers-and-casting-in-rust-9a847bfc398f</a></figcaption></figure><blockquote><strong><em>Note:</em> The article in here: </strong><a href="https://towardsdatascience.com/unsinged-signed-integers-and-casting-in-rust-9a847bfc398f"><strong>https://towardsdatascience.com/unsinged-signed-integers-and-casting-in-rust-9a847bfc398f</strong></a><strong> is actually a great resource to read, as it goes in details using Rust.</strong></blockquote><h3>Double 64b (8B), 128b (16B)</h3><p>Double is actually represented as 2 Signed Integers in most systems. So for 32-bit (4 Bytes) systems it is 64-bit (8 Bytes), while in 64-bit (8 Bytes) systems it is 128-bit (16 Bytes).</p><h3>Float — Exponent and Mentisa</h3><p>Floating points are numbers like <strong>3.414</strong>. So how are these represented? Well for a start it represented in the same 16-bit, 32-bit or 64-bit space like Integers, but unlike Integers it is not represented in the exact Binary representation, as its not memory efficient. Rather, its components are stored.</p><ol><li>First the number is converted to its Binary Format, so for our example 3.414: <strong>11.11001111.</strong></li><li>Then it is normalized into Implicit or Explicit Forms. Lets just use the Explicit Form right now: <strong>0.1111001111 X 2²</strong></li><li>The number is actually broken up into 3 separate components: (1) Sign (2) Exponent (3) Mentisa.</li></ol><p>So the Rightmost Bit (Most Significant Bit) is stores the sign, i.e., 0 for Positive, 1 for Negative.</p><p>For the Exponent, which in our case is 2, it is transformed into a processed called Biasing as Negative Exponents are not used. So, values from:</p><p>-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 are converted to <br>0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15. <br>For our case 2, it is converted to 10, which in Binary is <strong>1010</strong>.</p><p>And finally, the Mentisa is the number after the <strong>. </strong>decimal<strong> </strong>value which is<strong> 1111001111.</strong></p><p>So it is represented in 16-bit as <strong>0</strong> <strong>01010</strong> <strong>1111001111. <br></strong>So the exponent takes 5-bits.</p><p>Then for 32-bit as<strong> 0</strong> <strong>00001010</strong> <strong>00000000000001111001111. <br></strong>So the exponent takes 8-bits<strong>.</strong></p><h3>ASCII and Unicode</h3><p>We are done with numbers, which are represented as 16-bit, 32-bit or 64-bit Integer or Floating point, or their Double counter parts which are 64-bit or 128-bit as mentioned above. But how do we represent characters like ‘a’, ‘%’?</p><p>These were initially represented as 1 Bytes (8-bit) with an encoding rule called ASCII. Here is how the table looks:</p><figure><img alt="ASCII Table showing the Decimal, Hex and Characters from 0–127" src="https://cdn-images-1.medium.com/max/560/1*zNBtRoQMYe-DuCQLcK0aLw.gif" /><figcaption>Taken from <a href="https://www.fundraisersoftware.com/charmap.htm">https://www.fundraisersoftware.com/charmap.htm</a></figcaption></figure><p>So we can see that ‘a’ is represented as 97, or in bits 0110 0001, or in hex 0x61. <br>Similarly, ‘%’ is represented as 37, or in bits 0010 0101, or in hex 0x25.</p><p>This normal ASCII table goes from 0–127, which can be represented with 7-bits. What happened to another bit? Well for that we have the extended ASCII table:</p><figure><img alt="ASCII Table showing values from 128–255" src="https://cdn-images-1.medium.com/max/505/1*i727wK59FWsTbjiKj7YwjQ.gif" /><figcaption>Taken from <a href="https://www.fundraisersoftware.com/charmap.htm">https://www.fundraisersoftware.com/charmap.htm</a></figcaption></figure><p>But with time, we needed to represent many more characters and it was not possible to do with 8-bits (1 Byte) whose range is from 0 to 255. For this we needed a much more flexible approach which led to UTF-8 encoding, which is to use more than 1 Byte — 2/3 Bytes to represent these characters.</p><p><strong>Note:<em> Unicode is backwards compatible with ASCII. i.e., 0–127 Decimal Representation of Characters in Unicode is same as the ASCII Characters.</em></strong></p><p>So how does a character like ‘😀’ is represented?</p><p>Well here is what its Decimal Value looks like: <strong>128512</strong><br>And its Hex Value: 0x<strong>1F600</strong></p><p>There are total of 149,878 characters currently in the UTF-8 unicode standard.</p><h3>Conclusion</h3><p>It helps to learn how humans and computers represent information under the hood, and as it demystifies things at a deeper level. Hopefully this guide helped you to learn something new today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=406942418c05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcoding in Rust — Making Monotonic Stack and Queue Easy]]></title>
            <link>https://daviddecoding.medium.com/leetcoding-in-rust-making-monotonic-stack-and-queue-easy-72105eee9970?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/72105eee9970</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 08:47:25 GMT</pubDate>
            <atom:updated>2024-02-15T08:49:48.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcoding in Rust — Making Monotonic Stack and Queue Easy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tdEBaUpVx0otCcJhPnToQ.jpeg" /><figcaption>Image: Rust + Leetcode</figcaption></figure><p>This is an effort to document how I learned one of the most challenging concepts (which looks so easy at first glance) after Backtracking, which is Monotonically Increasing/Decreasing Stack and Queue problems.</p><p>These are challenging because it&#39;s not always apparent that using this data structure makes the solution any more accessible. So, let&#39;s start with the different patterns I have seen and break them down.</p><blockquote>Note: The reason I write these articles is two folds: (1) Showing that Rust is a fine language to do leetcode in, (2) Keep track of the problems and their solutions so that anyone can practice these several times to build muscle memory around the techniques being used.</blockquote><p><a href="https://leetcode.com/problems/daily-temperatures/">739. Daily Temperatures</a></p><p>In this pattern, you track the element index for which we need an event in the future. So, as we iterate over the input array, we first see if the current temperature is the next bigger element than the elements found previously. Then, we store the current index and the temperature in the Monotonically Decreasing Stack to see if we can find an element bigger than the current temperature on the right as we iterate over the rest of the input array.</p><pre>impl Solution {<br>    pub fn daily_temperatures(temperatures: Vec&lt;i32&gt;) -&gt; Vec&lt;i32&gt; {<br>        let (mut stk, mut res) = (Vec::&lt;(i32, usize)&gt;::new(), vec![0]);<br>        res.resize(temperatures.len(), 0);<br><br>        for (idx, temperature) in temperatures.iter().enumerate() {<br>            while stk.len() &gt; 0 &amp;&amp; stk[stk.len() - 1].0 &lt; *temperature {<br>                res[stk[stk.len() - 1].1] = (idx - stk[stk.len() - 1].1) as i32;<br>                stk.pop();<br>            }<br>            stk.push((*temperature, idx));<br>        }<br>        res<br>    }<br>}</pre><p><a href="https://leetcode.com/problems/maximum-width-ramp/">962. Maximum Width Ramp</a></p><p>In this pattern, you must use 2 separate steps to find the optimal solution. First, you find all the relevant ith elements from the left and track them in a Monotonically Decreasing Stack, and then find the relevant jth elements from the right as you calculate the maximum length of the ramp that can be formed between the ith and jth elements.</p><pre>Input: [6,0,8,2,1,5]<br><br>If you see carefully, the relevant ones are:<br>num1, num2 -&gt; idx1, idx2 -&gt; width<br>6,    8       0,    2       2<br>0,    8       1,    2       1<br>0,    2       1,    3       2<br>0,    1       1,    4       3<br>0,    5       1,    5       4<br>2,    5       3,    5       2<br>1,    5       4,    5       1<br><br>Now, here even though we can create the ramps 7 ways, we can see:<br>0,    8<br>0,    2<br>0,    1<br>Are not useful as we have a bigger element than 0 (which is 5) after all these.<br><br>Similarly,<br>2,    5<br>1,    5<br>Are also not relevant as we a smaller element than 2 and 1 (which is 0) before all these.<br><br>So, we can use a Monotonic Decreasing Stack to keep track of the elements 6, 0<br>which will be the only ith elements we care about.<br><br>Step 1:<br>-------<br>We iterate over each element, and if we encounter an element less than the top<br>element in the Monotonically Decreasing Stack, we add it in.<br><br>for (i, elem) in input.iter().enumerate() {<br>  if stack.len() == 0 || stack[stack.len() - 1].0 &gt; elem {<br>    stack.push((elem, i))<br>  }<br>}<br><br><br>Step 2:<br>-------<br>We iterate over each element, now from the right and if we encounter an element less than the top<br>element in the Monotonically Decreasing Stack, we calculate the maximum width, else we keep popping.<br><br>let mut maximum_width = 0;<br>for j in (0..(nums.len())).rev() {<br>  while stack.len() &gt; 0 &amp;&amp; stack[stack.len() - 1].0 &lt;= input[j] {<br>    let i = stack[stack.len() - 1].1;<br>    maximum_width = std::cmp::max(maximum_width, j - i);<br>    stack.pop();<br>  }<br>}<br></pre><p>So here is the final solution:</p><pre>impl Solution {<br>    pub fn max_width_ramp(nums: Vec&lt;i32&gt;) -&gt; i32 {<br>        let (mut maximum_width, mut stk) = (0, Vec::&lt;(i32, usize)&gt;::new());<br><br>        for (i, num) in nums.iter().enumerate() {<br>            if stk.len() == 0 || *num &lt; stk[stk.len() - 1].0 {<br>                stk.push((*num, i))<br>            }<br>        }<br><br><br>        for j in (0..(nums.len())).rev() {<br>            while stk.len() &gt; 0 &amp;&amp; nums[j] &gt;= stk[stk.len() - 1].0 {<br>                let i = stk[stk.len() - 1].1;<br>                maximum_width = std::cmp::max(maximum_width, j - i);<br>                stk.pop();<br>            }<br>        }<br><br>        maximum_width as i32<br>    }<br>}</pre><p><a href="https://leetcode.com/problems/maximum-subarray-min-product/">1856. Maximum Subarray Min-Product</a></p><p>This problem is relatively easy as you understand the 2 steps involved. First, you keep track of the increasing numbers in the input array in a monotonically increasing stack, and then in the next step, you have to unwind the stack to calculate the maximum min-product.</p><pre>impl Solution {<br>    pub fn max_sum_min_product(nums: Vec&lt;i32&gt;) -&gt; i32 {<br>        const MOD: u64 = 1e9 as u64 + 7;<br><br>        let mut stk = Vec::&lt;(u64, u64, usize)&gt;::new();<br><br>        let mut maximum = 0u64;<br>        // Step 1: Build the Monotonically Increasing Stack<br>        for (idx, num) in nums.iter().enumerate() {<br>            if stk.len() == 0 || stk[stk.len() - 1].0 &lt;= (*num as u64) {<br>                stk.push((*num as u64, *num as u64, idx));<br>                maximum = std::cmp::max(<br>                    maximum,<br>                    (*num as u64)<br>                );<br>            } else {<br>                let (mut current_sum, mut current_idx) = (0, 0);<br>                while stk.len() &gt; 0 &amp;&amp; stk[stk.len() - 1].0 &gt; (*num as u64) {<br>                    current_sum = current_sum + stk[stk.len() - 1].1;<br>                    current_idx = stk[stk.len() - 1].2;<br>                    let current_num = stk[stk.len() - 1].0;<br>                    maximum = std::cmp::max(<br>                        maximum,<br>                        current_sum * current_num<br>                    );<br>                    stk.pop();<br>                }<br>                stk.push((*num as u64, (*num as u64) + current_sum, current_idx));<br>            }<br>        }<br><br>        <br>        // Step 2: Unwind the stack to calculate the maximum<br>        let mut current_sum = 0u64;<br>        while stk.len() &gt; 0 {<br>            current_sum += stk[stk.len() - 1].1;<br>            maximum = std::cmp::max(<br>                maximum,<br>                current_sum * stk[stk.len() - 1].0<br>            );<br>            stk.pop();<br>        }<br><br>        (maximum % MOD) as i32<br>        <br>    }<br>}</pre><p><a href="https://leetcode.com/problems/beautiful-towers-ii/">2866. Beautiful Towers II</a></p><p>This problem is hard if you don’t know the trick, as it combines Prefix Sum, Suffix Sum, and Monotonically Increasing Stack problems.</p><p>First, we calculate the sums of the height of towers possible on the left by considering each element of the max_heights to be the peak element. <strong>The trick to understand here is the previous element can be less, equal, or greater.</strong> We can extend the prefix sum if the previous element is less or equal. But if the previous element was greater, then <strong>unfortunately, we need to look back to the previous element that was smaller than the current element, which can then be extended</strong>. This, by definition, becomes a Monotonically Increasing Stack problem.</p><pre>Input = [5,3,4,1,1]<br><br>Stk = []<br>LeftPrefixSums = [0,0,0,0,0]<br><br>Index 1:<br>There are no previous element, so we just add the max_height in PrefixSums.<br><br>LeftPrefixSums = [5,0,0,0,0]<br>Stk = [(5,0)]<br><br>Index 2:<br>The current element is smaller than the previous element, so we pop out. <br><br>Stk = []<br><br>And we also don&#39;t find any element in the stack, so we just multiply:<br>    (idx + 1) * max_height<br>And put that into the stack.<br><br><br>LeftPrefixSums = [5,6,0,0,0]<br>Stk = [(3,1)]<br><br>Index 3:<br>The current element is greater than the previous element, so we can continue<br>extending. <br><br>And we just add the PrefixSum of the previous element + current max_height.<br><br>LeftPrefixSums = [5,6,10,0,0]<br>Stk = [(3,1), (4,2)]<br><br>Index 4:<br>The current element is smaller than the previous element, <br>so we keep popping out.<br><br>Stk = []<br><br>And we also don&#39;t find any element in the stack, so we just multiply:<br>    (idx + 1) * max_height<br>And put that into the stack.<br><br>LeftPrefixSums = [5,6,10,4,0]<br>Stk = [(1,3)]<br><br>Index 5:<br>The current element is equal so we can extend.<br><br>LeftPrefixSums = [5,6,10,4,5]<br>Stk = [(1,3),(1,4)]<br><br></pre><p>Second, we calculate the sums of the height of towers possible on the right by considering each element of the max_heights as the peak element. We use a similar approach to what we used in building the previous prefix sum array.</p><pre>Input = [5,3,4,1,1]<br><br>Stk = []<br>RightPrefixSums = [0,0,0,0,0]<br><br>Index 1:<br>There are no previous element, so we just add the max_height in PrefixSums.<br><br>RightPrefixSums = [0,0,0,0,1]<br>Stk = [(1,4)]<br><br>Index 2:<br>The current element is equal to the next element, so we can extend. <br><br>RightPrefixSums = [0,0,0,2,1]<br>Stk = [(1,4),(1,3)]<br><br>Index 3:<br>The current element is greater than the previous element, so we can continue<br>extending. <br><br>And we just add the PrefixSum of the next element + current max_height.<br><br>RightPrefixSums = [0,0,6,1,1]<br>Stk = [(1,4),(1,3),(4,2)]<br><br>Index 4:<br>The current element is smaller than the next element, <br>so we keep popping out.<br><br>Stk = [(1,4),(1,3)]<br><br>We found the element that is smaller to the right, or next, <br>for rest we multiply:<br>    (stk[-1].1 - idx) * max_height<br>And put that into the stack.<br><br>RightPrefixSums = [0,8,6,1,1]<br>Stk = [(1,4),(1,3),(3,1)]<br><br>Index 5:<br>The current element is greater than the next element, so we extend.<br><br>RightPrefixSums = [13,8,6,1,1]<br>Stk = [(1,4),(1,3),(3,1),(5,0)]</pre><p>Then, iterate over the max_heights array to calculate the maximum sum possible.</p><p>Here is the final solution.</p><pre>impl Solution {<br>    pub fn maximum_sum_of_heights(max_heights: Vec&lt;i32&gt;) -&gt; i64 {<br>        let mut lConfigurations = Vec::&lt;i64&gt;::new();<br>        lConfigurations.resize(max_heights.len(), 0);<br><br>        let mut rConfigurations = Vec::&lt;i64&gt;::new();<br>        rConfigurations.resize(max_heights.len(), 0);<br><br>        let mut stk = Vec::&lt;(i32, usize)&gt;::new();<br>        for (idx, &amp;height) in max_heights.iter().enumerate() {<br>            while stk.len() &gt; 0 &amp;&amp; stk[stk.len() - 1].0 &gt; height {<br>                stk.pop();<br>            }<br>            if stk.len() &gt; 0 {<br>                lConfigurations[idx] += lConfigurations[stk[stk.len() - 1].1];<br>                lConfigurations[idx] += ((idx - stk[stk.len() - 1].1) as i64) * (height as i64);<br>            } else {<br>                lConfigurations[idx] += ((idx + 1) as i64) * (height as i64);<br>            }<br>            <br>            stk.push((height, idx));<br>        }<br><br>        stk = Vec::&lt;(i32, usize)&gt;::new();<br>        for (idx, &amp;height) in max_heights.iter().enumerate().rev() {<br>            while stk.len() &gt; 0 &amp;&amp; stk[stk.len() - 1].0 &gt; height {<br>                stk.pop();<br>            }<br>            if stk.len() &gt; 0 {<br>                rConfigurations[idx] += rConfigurations[stk[stk.len() - 1].1];<br>                rConfigurations[idx] += ((stk[stk.len() - 1].1 - idx) as i64) * (height as i64);<br>            } else {<br>                rConfigurations[idx] += ((rConfigurations.len() - idx) as i64) * (height as i64);<br>            }<br>            <br>            stk.push((height, idx));<br>        }<br><br>        let mut res = -1;<br>        for (idx, &amp;height) in max_heights.iter().enumerate() {<br>            res = std::cmp::max(<br>                res,<br>                lConfigurations[idx] + rConfigurations[idx] - (height as i64)<br>            );<br>        }<br><br>        res<br>    }<br>}</pre><p><a href="https://leetcode.com/problems/132-pattern/">456. 132 Pattern</a></p><p>This is another interesting problem requiring a unique idea that requires us to track the decreasing number and the minimum number that we saw before the top element in the same monotonically decreasing stack. This is a very tricky question, and it isn&#39;t easy to code it correctly even if you understand the solution, though the solution is not that large.</p><p>Here is what the steps would look like:</p><pre>Input = [2, 4, 1, 2, 3]<br>Stk = [(&lt;monotonically_decreasing_element&gt;, &lt;minimum_element_left&gt;)]<br><br><br>Index 0:<br>We don&#39;t have any minimum, so let&#39;s take <br>the current element at index 0 as the minimum.<br><br>Stk = [(2,2)]<br>There is just 1 element in the stack so we continue.<br><br>Index 1:<br>Now the element is bigger than the element at the top of the stack, so we pop.<br><br>Stk = []<br><br>Now the minimum element to the left is minimum of 2 and 4. So we add,<br><br>Stk = [(4,2)]<br><br>Index 2:<br>Next element is smaller than the top element on the stack, so we will just <br>add the current element and calculate the minimum. But before that,<br><br>Now that we also have an element in the stack, we need to see if the criteria is met.<br>minimum_element_left &lt; current_element &lt; element_at_the_top_of_the_stack.<br><br>2 &lt; 1 &lt; 4 # This is incorrect so criteria not met.<br><br>Stk = [(4,2),(1,2)]<br><br>Index 3:<br>Now the next element is bigger than the element at the top of the stack,<br>so we pop.<br><br>Stk = [(4,2)]<br><br>Now we still have more than 1 element, so lets check the criteria.<br><br>2 &lt; 2 &lt; 4 # This is incorrect so criteria not met.<br><br>Stk = [(4,2),(2,2)]<br><br>Index 4:<br>Now the next element is bigger than the element at the top of the stack,<br>so we pop.<br><br>Stk = [(4,2)]<br><br>As we still have more than 1 element, so lets check the criteria.<br><br>2 &lt; 3 &lt; 4 # Yes we have found the final element.<br><br>Return True</pre><p>And here is the final code in Rust:</p><pre>impl Solution {<br>    pub fn find132pattern(nums: Vec&lt;i32&gt;) -&gt; bool {<br>        let (mut stk, mut minimum) = (Vec::&lt;(i32, i32)&gt;::new(), nums[0]);<br><br>        for num in nums {<br>            while stk.len() &gt; 0 &amp;&amp; stk[stk.len() - 1].0 &lt;= num {<br>                stk.pop();<br>            }<br>            if stk.len() &gt; 0 &amp;&amp; num &gt; stk[stk.len() - 1].1 {<br>                return true;<br>            }<br>            stk.push((num, minimum));<br>            minimum = std::cmp::min(minimum, num)<br>        }<br>        return false;<br>    }<br>}</pre><p><a href="https://leetcode.com/problems/steps-to-make-array-non-decreasing/">2289. Steps to Make Array Non-decreasing</a></p><p>This problem is again very difficult to come up with, even if you know it requires a Monotonically Decreasing Stack. Like the above problem, you need to keep track of the number itself in the stack, and how many steps were completed before this number came up needs to be tracked.</p><pre>impl Solution {<br>    pub fn total_steps(nums: Vec&lt;i32&gt;) -&gt; i32 {<br>        let mut stk = Vec::&lt;(i32, i32)&gt;::new();<br><br>        for &amp;num in nums.iter().rev() {<br>            let mut times = 0;<br>            while stk.len() &gt; 0 &amp;&amp; num &gt; stk[stk.len() - 1].0 {<br>                times = std::cmp::max(times + 1, stk[stk.len() - 1].1);<br>                stk.pop();<br>            }<br>            stk.push((num, times));<br>        }<br><br>        let mut maximum = 0;<br>        for elem in stk {<br>            maximum = std::cmp::max(<br>                maximum,<br>                elem.1<br>            );<br>        }<br><br>        maximum<br>        <br>    }<br>}</pre><p><a href="https://leetcode.com/problems/jump-game-vi/">1696. Jump Game VI</a></p><p>This problem involves using a Monotonically Decreasing Queue instead of a Stack. The specialty of this data structure is that you compare against the top element while you add or remove it from the back of the queue.</p><p>You can try this problem using Dynamic Programming but the O(n*k) solution will cause TLE. So, we need to bring it down from k to something manageable. This is possible if we skip comparing all k elements and rather jump to the greater element&#39;s index. This can be done using a Monotonically Decreasing Queue, which we can implement using a Deque.</p><pre>Input = [1,-5,-20,4,-1,3,-6,-3]<br>k = 2<br><br>n = Length of the input = 8<br>DP = [0,0,0,0,0,0,0,-3]<br>Deque = [7] # We will be keeping the index in here, rather than the elements<br><br>We will then walk from the right to the left.<br><br>Index 6:<br>We compare the top element stored on the deque and store in DP and Deque:<br>DP[6] = Input[6] + DP[7] # 7 is the top index in the Deque<br><br>DP = [0,0,0,0,0,0,-9,-3]<br>Deque = [7,6]<br><br>Index 5:<br>DP[5] = Input[5] + DP[7]<br><br>DP = [0,0,0,0,0,0,-9,-3]<br>Deque = [5,7,6]<br><br>Index 4:<br>DP[4] = Input[4] + DP[5]<br><br>DP = [0,0,0,0,-1,0,-9,-3]<br>Deque = [5,4,7,6]<br><br>Index 3:<br>DP[3] = Input[3] + DP[5]<br><br>DP = [0,0,0,4,-1,0,-9,-3]<br>Deque = [3,5,4,7,6]<br><br>Index 2:<br>DP[2] = Input[2] + DP[3]<br><br>DP = [0,0,-16,4,-1,0,-9,-3]<br>Deque = [3,5,4,7,6,2]<br><br>Index 1:<br>DP[1] = Input[1] + DP[3]<br><br>DP = [0,-1,-16,4,-1,0,-9,-3]<br><br>Now something interesting is going to happen, we need to pop elements from the<br>back to keep the queue in Decreasing order.<br>Deque = [3,5,4,1] <br><br>Index 0:<br>Now another interesting thing we need to do is we need to pop elements from<br>the front that is beyond Index + k = 0 + 2 = 2:<br>Deque = [1]<br><br>Then we calculate,<br>DP[0] = Input[0] + DP[1]<br><br>DP = [0,-1,-16,4,-1,0,-9,-3]<br><br>And finally the result is DP[0] = 0.</pre><p>Here is the final code:</p><pre>use std::collections::VecDeque;<br><br>impl Solution {<br>    pub fn max_result(nums: Vec&lt;i32&gt;, k: i32) -&gt; i32 {<br>        let n = nums.len();<br>        let mut dp = vec![0];<br>        dp.resize(n, 0);<br>        dp[n - 1] = nums[n - 1];<br><br>        let mut q = VecDeque::&lt;usize&gt;::new();<br>        q.push_back(n - 1);<br><br>        for i in (0..n-1).rev() {<br>            while q.front().unwrap() - i &gt; (k as usize) {<br>                q.pop_front();<br>            }<br>            dp[i] = nums[i] + dp[*q.front().unwrap()];<br>            while q.len() &gt; 0 &amp;&amp; dp[*q.back().unwrap()] &lt; dp[i] {<br>                q.pop_back();<br>            }<br>            q.push_back(i);<br>        }<br><br>        dp[0]<br>    }<br>}</pre><h3>Bonus</h3><p>I am including these problems here because they require other steps before you can use Monotonic Stack or Queue. But using Monotonic Stack or Queue is pretty straightforward if you can get to the first step.</p><p><a href="https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/">1996. The Number of Weak Characters in the Game</a></p><p>To solve this, you first need to sort the input by the first element in the ascending order and then by the second element in the descending order. After that, you can maintain a Monotonic Decreasing Stack where the elements will have the first element in the Increasing order while the second element will be in the Decreasing order in the Stack.</p><pre>impl Solution {<br>    pub fn number_of_weak_characters(mut properties: Vec&lt;Vec&lt;i32&gt;&gt;) -&gt; i32 {<br>        properties.sort_unstable_by(|a, b| {<br>            if a[0] != b[0] {<br>                a[0].cmp(&amp;b[0])<br>            } else {<br>                b[1].cmp(&amp;a[1])<br>            }<br>        });<br><br>        let (mut stk, mut res) = (Vec::&lt;&amp;Vec&lt;i32&gt;&gt;::new(), 0);<br><br>        for i in 0..properties.len() {<br>            while stk.len() &gt; 0 &amp;&amp; stk[stk.len()-1][1] &lt; properties[i][1] {<br>                stk.pop();<br>                res += 1;<br>            }<br>            stk.push(&amp;properties[i]);<br>        }<br><br>        res<br>    }<br>}</pre><p><a href="https://leetcode.com/problems/remove-k-digits/">402. Remove K Digits</a></p><p>This problem is very easy to implement but hard to get to in terms of the solution. We need to create a Monotonically Increasing Stack of digits till we run out of k digits to remove.</p><pre>impl Solution {<br>    pub fn remove_kdigits(num: String, k: i32) -&gt; String {<br>        let (mut stk, mut _k) = (Vec::&lt;char&gt;::new(), k);<br><br>        for digit in num.chars() {<br>            let digit_in_u32: u32 = digit.to_digit(10).unwrap();<br><br>            while stk.len() &gt; 0 &amp;&amp; _k &gt; 0 {<br>                let top = stk[stk.len() - 1].to_digit(10).unwrap();<br>                if top &lt;= digit_in_u32 {<br>                    break;<br>                }<br>                _k -= 1;<br>                stk.pop();<br>            }<br>            stk.push(digit);<br>        }<br><br>        while _k &gt; 0 {<br>            stk.pop();<br>            _k -= 1;<br>        }<br><br>        // !----- These can be done better. May be with a deque ----!<br>        stk.reverse();<br>        while stk.len() &gt; 0 &amp;&amp; stk[stk.len() - 1] == &#39;0&#39; {<br>            stk.pop();<br>        }<br>        stk.reverse();<br>        // !----------- Till here ---------!<br><br>        if stk.len() == 0 {<br>            stk.push(&#39;0&#39;);<br>        }<br><br>        stk.iter().collect()<br>    }<br>}</pre><h3>More things you might be interested in</h3><h4>Leetcoding in Rust</h4><ul><li><a href="https://medium.com/@daviddecoding/leetcoding-in-rust-curious-case-of-sub-arrays-and-its-relationship-with-k-5c642461d79f"><strong>Curious case of Sub Arrays and its relationship with K</strong></a></li></ul><h4>Coding</h4><ul><li><a href="https://medium.com/@daviddecoding/must-know-coding-and-problem-solving-concepts-to-ace-your-big-tech-interview-2f8745decd58"><strong>Must Know Coding and Problem-Solving Concepts to Ace Your Big Tech Interview</strong></a></li></ul><h4>System Design</h4><ul><li><a href="https://daviddecoding.medium.com/system-design-coding-it-up-f085a898a110"><strong>Big Tech Interview: Implementations of Alex Xu’s System Design Algorithms (Python) — Part 1</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72105eee9970" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcoding in Rust—Curious case of Sub Arrays and its relationship with K]]></title>
            <link>https://daviddecoding.medium.com/leetcoding-in-rust-curious-case-of-sub-arrays-and-its-relationship-with-k-5c642461d79f?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c642461d79f</guid>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 14:26:34 GMT</pubDate>
            <atom:updated>2024-02-15T08:50:52.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1FZhvLpCBa2WTW6NqK9Pg.jpeg" /><figcaption>Image: Rust + Leetcode</figcaption></figure><blockquote>Getting started with Graphs, Trees, and BSTs is harder, but it gets easier with practice. On the other hand, getting started with Arrays and LinkedLists is always easy, but it gets harder as you do more problems.<br> <br>- By an average Leetcoder (Failed FAANG Interviewee)</blockquote><p>Love stories of the Sub Array and K can be found all over Leetcode and is nothing new to an average Leetcoder. But the more you think you are done with their story, the more they pull you into their lore.</p><p>It all started with a naive Subarray in the Medium section of Leetcode in search of some K. With practice, you know how it all ends, but do you?</p><ol><li><strong>Subarray/Substring</strong> — Use Sliding Window</li><li><strong>Subsequence</strong> — Use Dynamic Programming</li><li><strong>Subsets</strong> — Use Backtracking</li></ol><p>And you merrily go your way and live happily ever after. You wish it ended like that as you turn the page to face the Hards. You are greeted with a love affair with all the ingredients for making a whole DS&amp;A chapter.</p><h3>Chapter 1 — The Sliding Window</h3><p><a href="https://leetcode.com/problems/subarrays-with-k-different-integers/">992. Subarrays with K Different Integers</a></p><p>This problem uses a Sliding Window but with an exciting twist. But before that, we need to understand the attractive property of counting subarrays.</p><p>Let&#39;s find the subarrays where the number of distinct elements (integers) is Atmost K (let&#39;s take the value of K = 3). How can we do that?</p><pre>Input = [1, 2, 3], K = 3<br><br>Then if we iterate over all possible solutions, it will be:<br>[1],<br>[2],<br>[3],<br>[1, 2],<br>[2, 3],<br>[1, 2, 3]<br><br>So, the count is 6. <br><br>But how can we count this if this K was large and Input size was arbitarylarge?</pre><p>Here is the sudo code for how to count subarrays from 0 to n elements with some constraints (let&#39;s call that invalid_state()):</p><pre>let inpt = vec![1, 2, 3]<br>let n = inpt.len() # 3<br><br>let (mut i, mut j, mut count) = (0usize, 0usize, 0usize)<br><br>fn&lt;T&gt; modify_state&lt;T&gt;(some_state: T, index: i32) {<br>    ....<br>}<br><br>fn&lt;T&gt; invalid_state&lt;T&gt;(some_state: T) -&gt; bool {<br>    true<br>}<br><br>while j &lt; n {<br>    modify_state(j, some_state);<br>    while i &lt; j &amp;&amp; invalid_state(some_state) { // When constraints fail<br>        modify_state(i, some_state);<br>        i += 1;<br>    }<br>    count += j - i + 1;<br>    j += 1;<br>}<br><br>return count</pre><p>So, we arrive at a general solution to count the number of subarrays with almost every size that meets some constraints. You can put anything in here from [(1) <em>Atmost Distinct K Elements</em>, (2) <em>Elements divisible by 3</em>, (3) <em>Even integers…</em>] in place of <strong><em>invalid_state</em></strong>. In our case, we will check if the number of distinct elements is almost K.</p><p>The other concept is counting Exactly K Elements (Not Atmost K). There are several ways to do this:</p><ol><li><strong>Total Subarrays</strong> <em>minus</em> <strong>Total subarrays that do not contain Exactly K elements</strong>.</li><li><strong>Total Subarrays contain Atmost K Distinct Elements </strong><em>minus</em><strong> Total Subarrays that contain Atmost K — 1 Distinct Elements.</strong></li><li><strong>Total Subarrays contain Atleast K+1 Distinct Elements</strong> <em>minus</em> <strong>Total Subarrays that contain Atleast K Distinct Elements</strong>.</li></ol><p>We can leverage any of the above ways to find <strong>Exactly</strong> K. But as we already know how to find Atmost K, we can use (2) to solve the problem. You should be able to solve it now on your own, but here is the solution.</p><pre>use std::collections::HashMap;<br><br>impl Solution {<br><br>    fn subarrays_with_atmost_k_distinct(nums: &amp;Vec&lt;i32&gt;, k: i32) -&gt; i32 {<br>        if k == 0 {<br>            return 0;<br>        }<br><br>        let (mut i, mut j, mut res, mut hashmap) = (0usize, 0usize, 0usize, HashMap::&lt;i32, i32&gt;::new());<br><br>        while j &lt; nums.len() {<br>            let key_j = nums[j];<br>            if !hashmap.contains_key(&amp;key_j) {<br>                hashmap.insert(key_j, 0);<br>            }<br>            hashmap.insert(key_j, *hashmap.get(&amp;key_j).unwrap() + 1);<br><br>            while i &lt; j &amp;&amp; hashmap.len() &gt; (k as usize) {<br>                let key_i = nums[i];<br>                hashmap.insert(key_i, *hashmap.get(&amp;key_i).unwrap() - 1);<br>                if *hashmap.get(&amp;key_i).unwrap() == 0 {<br>                    hashmap.remove(&amp;key_i);<br>                }<br>                i += 1;<br>            }<br>            res += j - i + 1;<br>            j += 1;<br>        }<br><br>        res as i32<br>    }<br>    pub fn subarrays_with_k_distinct(nums: Vec&lt;i32&gt;, k: i32) -&gt; i32 {<br>        return Self::subarrays_with_atmost_k_distinct(&amp;nums, k) - Self::subarrays_with_atmost_k_distinct(&amp;nums, k - 1);<br>    }<br>}</pre><h3>Chapter 2 — The Tale of Two Pointers</h3><p><a href="https://leetcode.com/problems/maximum-score-of-a-good-subarray/">1793. Maximum Score of a Good Subarray</a></p><p>This problem looks like a simple subarray problem with k elements, but it&#39;s nothing like that. What the problem is asking you to do is <strong>include the kth element </strong>in the final subarray<strong>.</strong></p><p>So you start from the kth element and compare the elements on the left and right to see if they change the min element, and if it does, then does it produce the maximum value? It&#39;s a Two-pointers problem, where you extend the left and right indexes based on the criteria.</p><p>Interestingly, the problem is that <strong>(j — i + 1) can never go down</strong> as you can increase j to the right or decrease i to the left. So, what matters in the problem is the minimum elements to the left and right. So, if the left element is greater than the element on the right, we can try to expand on the left and see if we get a better result. Otherwise, we can expand on the right to see if we get a better result. This is a Two Pointers + Greedy problem.</p><pre>use std::cmp;<br><br>impl Solution {<br>    pub fn maximum_score(nums: Vec&lt;i32&gt;, k: i32) -&gt; i32 {<br>        let (mut i, mut j, mut curMin, mut res) = (k as usize, k as usize, nums[k as usize] as usize, nums[k as usize] as usize);<br><br>        while j &lt; nums.len() - 1 || i &gt; 0 {<br>            let left = if (i &gt; 0) { nums[i - 1] as usize } else { 0 as usize };<br>            let right = if (j &lt; nums.len() - 1) { nums[j + 1] as usize } else { 0 as usize };<br><br>            if left &gt; right {<br>                i -= 1;<br>                curMin = cmp::min(curMin, left);<br>            } else {<br>                j += 1;<br>                curMin = cmp::min(curMin, right)<br>            }<br><br>            res = cmp::max(res, curMin * (j - i + 1))<br>        }<br>        res as i32<br>    }<br>}</pre><h3>Chapter 3 — The Order of the Deque</h3><p><a href="https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/">862. Shortest Subarray with Sum at Least K</a></p><p>This problem resembles the Shortest Subarray with Sum K (or Exactly K), which a Sliding Window can easily solve. However, this problem is very different as we must find the Shortest Subarray with Sum K or above. This means if K is 10, and the Shortest Subarray we get with Sum 10 is 20, while we have another Subarray with Sum 11 but the size of the Subarray is 19, then the answer will be 19.</p><p>The Brute force way of doing this would be to get all Subarrays, filter down to Subarrays whose Sum is K or above, and then find the Subarray with the minimum size. But this will be O(n²). We need to do better as the maximum length is of order 10⁵.</p><p>One of the optimal approaches is to use a Prefix Sum array to calculate the Subarray Sums. How does that work? Let me make that clear here:</p><pre>Input = [2,-1,2] # Given Subarray<br>K = 3<br><br>PrefixSums = [0, 2, 1, 3] # We calculate the Prefix Sums (Cumulative SSumSums)</pre><p>After we have the Prefix Sums, we can easily calculate the Subarrays. For example, let&#39;s say we want to know the Sum of the Subarray from Index = 1 to Index = 2.</p><pre>sumOfSubarrayIndexOneToTwo = PrefixSums[2 + 1] - PrefixSums[1]<br>                           = PrefixSums[3] - PrefixSums[1]<br>                           = 3 - 2<br>                           = 1<br><br>We can check manually that the sum of subarray [-1, 2] is indeed equal to 1. </pre><p>Now that we know how to calculate the Sum of Subarrays from Prefix Sum, we need to find the Index till we need to stretch the Subarray for each Index till the Sum is equal to or greater than K. Basically, we need to find the two indexes between which the Sum is equal to or greater than K.</p><p>For this, we have this equation:</p><pre>PrefixSum[end + 1] - PrefixSum[start] &gt;= K</pre><p>We can rewrite this as:</p><pre>PrefixSum[end + 1] - K &gt;= PrefixSum[start]</pre><p>So we can iterate through the Prefix Sums by each Index and then iterate again till that Index to see which start value satisfies the above equation. Then the size of the Subarray will be end + 1 — start. Great, but now the problem is we are still making two loops, so the Runtime will still be O(n²); it doesn’t help.</p><p>But this is where we need the power of a data structure that can keep track of values we care about and discard those we don’t so that we don’t end up iterating over them again.</p><p>Let’s try to visualize this:</p><pre>Input = [2,-1,2] # Given Subarray<br>K = 3<br><br>PrefixSums = [0, 2, 1, 3] # We calculate the Prefix Sums (Cumulative Sums)<br><br>So for each Index, <br>let&#39;s apply the above equation (PrefixSums[end + 1] - K &gt;= PrefixSums[start]):<br><br>1. Index = 0, End = 0:<br>--------------------------<br>  PrefixSums[0 + 1] - K<br>  =&gt; 2 - 3<br>  =&gt; -1<br>Is there a value in the PrefixSums till Index = 0, that has the value -1 or less? No.<br>So nothing to do. Let&#39;s move on.<br><br>2. Index = 1, End = 1:<br>--------------------------<br>  PrefixSums[1 + 1] - K<br>  =&gt; 1 - 3<br>  =&gt; -2<br>Is there a value in the PrefixSums till Index = 1, that has the value -2 or less? No.<br>So nothing to do. Let&#39;s move on.<br><br>2. Index = 1, End = 1:<br>--------------------------<br>  PrefixSums[2 + 1] - K<br>  =&gt; 3 - 3<br>  =&gt; 0<br>Is there a value in the PrefixSums till Index = 2, that has the value 0 or less? Yes.<br>The value at index = 0, has the value = 0 in the PrefixSums. <br>So the size of the Subarray that satisfies the condition is 2 + 1 - 0 = 3<br><br>And 3 is the answer.<br></pre><p>In this example, we didn’t need to iterate over every value in the PrefixSum array for each Index as the first element had satisfied the condition. Still, let’s take the following example (<a href="https://www.youtube.com/watch?v=Jm-ZTGd6TOQ">Taken from the explanation here</a>):</p><pre>Input = [3, 5, 2, 1, -6, 7, 1, 8]<br>K = 8<br><br>PrefixSums = [0, 3, 8, 10, 11, 5, 12, 13, 21]<br><br>1. Index = 0, End = 0:<br>--------------------------<br>  PrefixSums[0 + 1] - K<br>  =&gt; 3 - 8<br>  =&gt; -5<br>So do we have -5 or less in the PrefixSums? No. We move on.<br><br>2. Index = 1, End = 1:<br>--------------------------<br>  PrefixSums[1 + 1] - K<br>  =&gt; 8 - 8<br>  =&gt; 0<br>So do we have -5 or less in the PrefixSums? Yes. <br>We record the size = 1 + 1 - 0 = 2<br><br>3. Index = 2, End = 2:<br>--------------------------<br>  PrefixSums[2 + 1] - K<br>  =&gt; 10 - 8<br>  =&gt; 2<br>So do we have 2 or less in the PrefixSums? Yes, its 0.<br>But hold on we have already used 0 and if we use it again the size of the <br>subarray is going to be larger than what we have found earlier. <br>Size = 2 + 1 - 0 = 3.<br>So that doesn&#39;t help. <br>Why not just discard this value when we get a match as another match will not<br>give us a smaller size subarray. Remember we need to find the Shortest Subarray.</pre><p>This is very interesting. If we find a matching pair, anything after it will not add any value if we take the same start Index in the PrefixSum, as it will be bigger. Ok, so let’s remove it from the PrefixSums.</p><pre>2. Index = 1, End = 1:<br>--------------------------<br>  PrefixSums[1 + 1] - K<br>  =&gt; 8 - 8<br>  =&gt; 0<br>So do we have -5 or less in the PrefixSums? Yes. <br>We record the size = 1 + 1 - 0 = 2.<br><br>Lets remove the element at Index = 0.<br><br>The new PrefixSums subarray:<br><br>PrefixSums = [N/A, 3, 8, 10, 11, 5, 12, 13, 21]. Ok lets continue.<br><br>3. Index = 2, End = 2:<br>--------------------------<br>  PrefixSums[2 + 1] - K<br>  =&gt; 10 - 8<br>  =&gt; 2<br>So do we have 2 or less in the PrefixSums? No. We move on.<br><br>4. Index = 3, End = 3:<br>--------------------------<br>  PrefixSums[3 + 1] - K<br>  =&gt; 11 - 8<br>  =&gt; 3<br>So do we have 3 or less in the PrefixSums? Yes.<br>We record the size = 3 + 1 - 1 = 3. But last time we got 2, so this is not the<br>shortest. So we can discard it.<br><br>Lets remove the element at Index = 1.<br><br>The new PrefixSums subarray:<br><br>PrefixSums = [N/A, N/A, 8, 10, 11, 5, 12, 13, 21]. Ok lets continue.<br><br>5. Index = 4, End = 4:<br>--------------------------<br>  PrefixSums[4 + 1] - K<br>  =&gt; 5 - 8<br>  =&gt; -3<br>So do we have 3 or less in the PrefixSums? No. We move on.<br><br>6. Index = 5, End = 5<br>--------------------------<br>  PrefixSums[5 + 1] - K<br>  =&gt; 12 - 8<br>  =&gt; 4<br>So do we have 4 or less in the PrefixSums? No. We move on.<br><br>7. Index = 6, End = 6<br>--------------------------<br>  PrefixSums[6 + 1] - K<br>  =&gt; 13 - 8<br>  =&gt; 5<br>So do we have 5 or less in the PrefixSums? Yes.<br>We record the size = 6 + 1 - 5 = 2. But this same as 2. <br><br>Lets remove the element at Index = 5.<br><br>The new PrefixSums subarray:<br><br>PrefixSums = [N/A, N/A, 8, 10, 11, N/A, 12, 13, 21]. Ok lets continue.<br><br><br><br><br><br>But something interesting has happened now, the elements before 5: <br>8, 10, 11 got skipped. <br>Do we need to keep them in here anymore?<br>Even if we do get 8 or 10 or 11 the size of the subarray is going to be bigger<br>than 2. So what is the point of keeping them?<br>We can also just nullify them.<br><br>PrefixSums = [N/A, N/A, N/A, N/A, N/A, N/A, 12, 13, 21]</pre><p>So we see two separate ways we need to nullify the elements: whatever comes to the left when it matches, or else if elements got skipped, we might have to go back from the right and nullify the elements.</p><p>This is where we see the power of the Deque. Instead of keeping the PrefixSums in an array, what if we add them in a Deque? Then, we don’t need to reiterate the nullified values; we can remove them with O(1) operation.</p><p>Also, we don’t need to precalculate the entire PrefixSums; we only need the PrefixSum at the end + 1 and whatever comes before. So, we can keep a single variable to store the PrefixSum of end + 1 and then add it to our Deque after we compare the values already in the Deque.</p><p>So, now that we understand the solution let&#39;s code it up with a Deque.</p><pre>impl Solution {<br>    pub fn shortest_subarray(nums: Vec&lt;i32&gt;, k: i32) -&gt; i64 {<br>        let mut deq: std::collections::VecDeque&lt;(i64, i64)&gt; = std::collections::VecDeque::new();<br>        deq.push_back((0, -1));<br><br>        let (mut prefixSum, mut res) = (0 as i64, i64::MAX);<br><br>        for (idx, val) in nums.iter().enumerate() {<br>            prefixSum += (*val as i64);<br>            while deq.len() &gt; 0 &amp;&amp; prefixSum &lt;= deq.back().unwrap().0 {<br>                deq.pop_back();<br>            }<br><br>            while deq.len() &gt; 0 &amp;&amp; prefixSum - (k as i64) &gt;= deq.front().unwrap().0 {<br>                res = std::cmp::min(res, (idx as i64) - deq.front().unwrap().1);<br>                deq.pop_front();<br>            }<br>            deq.push_back((prefixSum, idx as i64))<br>        }<br><br>        if res == i64::MAX {<br>            return -1;<br>        }<br><br>        res<br>    }<br>}</pre><h3>Chapter 4 — The Unusual Sliding Window</h3><p><a href="https://leetcode.com/problems/count-subarrays-with-fixed-bounds/">2444. Count Subarrays With Fixed Bounds</a></p><p>This problem can be solved by the Sliding Window technique but with a very different twist. This will require us to keep track of 4 different indexes, unlike a usual Sliding Window problem where we keep track of 2 indexes.</p><p>If you think about the problem, you must keep track of a few states, i.e., (1) Where does the window start? (2) Where does it end? (3) Have we found the element with the minimum value, which is given as minK, and (4) have we found the element with the maximum value, which is given as maxK?</p><p>Let&#39;s try first to solve the problem where all elements are between minK and maxK. Then, try to extend the solution to the actual problem.</p><pre>input = [3,2,1,2,1,5,3]<br>minK = 1, maxK = 5<br><br>So we can see all elements are between minK (1) and maxK (5). <br>So how many valid subarrays possible?<br><br>Subarrays:<br>[3], [2], [1], [2], [1], [5], [3] -&gt;           X Not valid<br>[3, 2], [2, 1], [1, 2], [2, 1], [5, 3] -&gt;      X Not valid<br>[1, 5] -&gt;                                        Valid!<br>[3, 2, 1], [2, 1, 2], [1, 2, 1] -&gt;             X Not valid<br>[2, 1, 5], [1, 5, 3] -&gt;                          Valid! <br>[3, 2, 1, 2] -&gt;                                X Not valid<br>[2, 1, 2, 1] -&gt;                                X Not valid<br>[1, 2, 1, 5], [2, 1, 5, 3] -&gt;                    Valid!<br>[3, 2, 1, 2, 1] -&gt;                             X Not valid<br>[2, 1, 2, 1, 5], [1, 2, 1, 5, 3] -&gt;              Valid!<br>[3, 2, 1, 2, 1, 5], [2, 1, 2, 1, 5, 3] -&gt;        Valid!<br>[3, 2, 1, 2, 1, 5, 3]                            Valid!<br><br>So there are only 10 solutions here.<br><br>One thing to notice is if we see the solutions and see it from the right:<br>            [1, 5]<br>         [2, 1, 5]<br>      [1, 2, 1, 5]<br>   [2, 1, 2, 1, 5]<br>[3, 2, 1, 2, 1, 5]<br><br>So if we see from the right ones we have both the elements minK and maxK, <br>then we can extend it till by any number of element and it will be valid.<br><br>            [1, 5, 3]<br>         [2, 1, 5, 3]<br>      [1, 2, 1, 5, 3]<br>   [2, 1, 2, 1, 5, 3]<br>[3, 2, 1, 2, 1, 5, 3]<br><br>Similarly, if we have both minK and maxK, we can also extend it to the right,<br>and extend it as much as possible.<br><br>So this can be thought of as a sliding window, where we take i, j as the<br>start and end of the dynamically sized sliding window, where we move j from<br>left to right, keep track of the number of times we get minK and maxK. Then we shrink<br>the sliding window, i.e. move i to the right till we have both 1 or more minK<br>and maxK element tracked. Then we can add i + 1 to the result. We do this<br>everytime we move j to the right and we still have 1 or more minK and maxK<br>tracked.<br><br>We take a hashmap = {} to track minK and maxK. We then take 2 pointers to be<br>the 2 ends of sliding window i, j.<br><br>[3, 2, 1, 2, 1, 5, 3]         {}<br> ^^<br> ij<br><br>Then,<br>[3, 2, 1, 2, 1, 5, 3]         {}<br> ^  ^<br> i  j<br><br>Then,<br>[3, 2, 1, 2, 1, 5, 3]         {1: 1} # We have found minK (1) and 1 times<br> ^     ^<br> i     j<br><br>Then,<br>[3, 2, 1, 2, 1, 5, 3]         {1: 1}<br> ^        ^<br> i        j<br><br>Then,<br>[3, 2, 1, 2, 1, 5, 3]         {1: 2} # We found another minK<br> ^           ^<br> i           j<br><br>Then,<br>[3, 2, 1, 2, 1, 5, 3]         {1: 2, 5: 1} # Now we have both 1 and 5<br> ^              ^<br> i              j<br><br>Now we start moving i,<br>[3, 2, 1, 2, 1, 5, 3]         {1: 2, 5: 1}<br>    ^           ^<br>    i           j<br><br>Then,<br>[3, 2, 1, 2, 1, 5, 3]         {1: 2, 5: 1}<br>       ^        ^<br>       i        j<br><br>Now we remove 1 minK, and keep moving<br>[3, 2, 1, 2, 1, 5, 3]         {1: 1, 5: 1}<br>          ^     ^<br>          i     j<br><br>Then,<br>[3, 2, 1, 2, 1, 5, 3]         {1: 1, 5: 1}<br>             ^  ^<br>             i  j<br><br>Now if we move i one more time to the right we will no longer have<br>a valid subarray so we stop and add i + 1 to the result<br><br>result += i + 1 = 4 + 1 = 5<br><br>Now we can move j again,<br>[3, 2, 1, 2, 1, 5, 3]         {1: 1, 5: 1}<br>             ^     ^<br>             i     j<br><br>Now we check again and find we meet the criteria, and try to move i,<br>but moving i will again lead to invalid subarray, we again collect the<br>results with adding i + 1 to the result<br><br>result += i + 1 = 5 + 4 + 1 = 10<br><br>And finally we have found the result.</pre><p>Even though we have found the result, this is still O(n²). But we can do another interesting optimization if we understand an interesting property of the iteration. We can keep track of the last minK and maxK position instead of the count, and every time we have both minK and maxK position, we add the minimum of the position of minK and maxK. It&#39;s the same thing, but we can eliminate the i-pointer iteration.</p><pre>[3, 2, 1, 2, 1, 5, 3]     minK_pos = -1, maxK_pos = -1 # We track the positions of minK and maxK<br> ^<br> j<br><br>Then,<br>[3, 2, 1, 2, 1, 5, 3]     minK_pos = -1, maxK_pos = -1<br>    ^<br>    j<br><br>Now we found the first minK position,<br>[3, 2, 1, 2, 1, 5, 3]     minK_pos = 2, maxK_pos = -1<br>       ^<br>       j<br><br>Then,<br>[3, 2, 1, 2, 1, 5, 3]     minK_pos = 2, maxK_pos = -1<br>          ^<br>          j<br><br>We found the second/last minK position,<br>[3, 2, 1, 2, 1, 5, 3]     minK_pos = 4, maxK_pos = -1<br>             ^<br>             j<br><br>Next we also found the maxK position, now we can add min(minK_pos, maxK_pos) + 1<br>[3, 2, 1, 2, 1, 5, 3]     minK_pos = 4, maxK_pos = 5<br>                ^<br>                j<br><br>Now we add min(minK_pos, maxK_pos) + 1 = 4 + 1,<br>result += 5<br><br>Then, we continue<br>[3, 2, 1, 2, 1, 5, 3]     minK_pos = 4, maxK_pos = 5<br>                   ^<br>                   j<br><br>We still have both the same positions, so we can again add the same<br>result += min(minK_pos, maxK_pos) + 1 = 5 + 4 + 1 = 10</pre><p>Awesome, we have found an algorithm to find all subarrays between minK and maxK if all elements of the original array are between minK and maxK. We now need the final piece, that is, when we have elements not within minK and maxK.</p><p>This is very easy to see,</p><pre>Lets say this is the new input array: [3, 2, 1, 2, 7, 1, 5, 3]<br>Here we can see 7 which wasn&#39;t there before, and it does not fall within minK (1) and maxK (5)<br><br>So we can never include this 7 in our subarrays, and we can see this as a partition.<br><br>Our answers are going to be within the 2 splits:<br>[3, 2, 1, 2] and [1, 5, 3]<br><br>And instead of adding, min(minK_pos, maxK_pos) + 1 to the result, we need to add<br><br>min(minK_pos, maxK_pos) - invalid_pos <br>  where invalid_pos is the last index of element that splits the array<br><br>Also remember when we split the array the minK_pos and maxK_pos has to be reset.<br><br>Lets try the new algorithm for the input: [3, 2, 1, 2, 7, 1, 5, 3]<br><br>[3, 2, 1, 2, 7, 1, 5, 3]        minK_pos = -1, maxK_pos = -1, invalid_pos = -1<br> ^<br> j<br><br>Then,<br>[3, 2, 1, 2, 7, 1, 5, 3]        minK_pos = -1, maxK_pos = -1, invalid_pos = -1<br>    ^<br>    j<br><br>We found the first minK pos,<br>[3, 2, 1, 2, 7, 1, 5, 3]        minK_pos = 2, maxK_pos = -1, invalid_pos = -1<br>       ^<br>       j<br><br>Then,<br>[3, 2, 1, 2, 7, 1, 5, 3]        minK_pos = 2, maxK_pos = -1, invalid_pos = -1<br>          ^<br>          j<br><br><br>Now we hit the invalid number, so we track that and reset, basically split<br>[3, 2, 1, 2, 7, 1, 5, 3]        minK_pos = -1, maxK_pos = -1, invalid_pos = 4<br>             ^<br>             j<br><br>We found the first minK pos,<br>[3, 2, 1, 2, 7, 1, 5, 3]        minK_pos = 5, maxK_pos = -1, invalid_pos = 4<br>                ^<br>                j<br><br>Now we found the maxK pos too,<br>[3, 2, 1, 2, 7, 1, 5, 3]        minK_pos = 5, maxK_pos = 6, invalid_pos = 4<br>                   ^<br>                   j<br><br>So we now add min(minK_pos, maxK_pos) - invalid_pos to result,<br>result += min(minK_pos, maxK_pos) - invalid_pos = min(5, 6) - 4 = 5 - 4 = 1<br><br>Then,<br>[3, 2, 1, 2, 7, 1, 5, 3]        minK_pos = 5, maxK_pos = 6, invalid_pos = 4<br>                      ^<br>                      j<br><br>So nothing changed, and we still have minK_pos and maxK_pos found and not reset,<br>so we add again min(minK_pos, maxK_pos) - invalid_pos to the result.<br><br>result += min(minK_pos, maxK_pos) - invalid_pos = 1 + 1 = 2<br><br>So now we result 2. And we can also manually verify:<br>   <br>   [1, 5]<br>[1, 5, 3]<br>are the 2 valid subarrays.</pre><p>Now, here is the implementation,</p><pre>use std::cmp::{min, max};<br><br>impl Solution {<br>    pub fn count_subarrays(nums: Vec&lt;i32&gt;, minK: i32, maxK: i32) -&gt; i64 {<br>        let (mut j, mut minK_pos, mut maxK_pos, mut invalid_pos, mut res) = (0usize, -1i64, -1i64, -1i64, 0i64);<br><br>        while j &lt; nums.len() {<br>            if nums[j] &lt; minK || nums[j] &gt; maxK {<br>                minK_pos = -1i64;<br>                maxK_pos = -1i64;<br>                invalid_pos = j as i64;<br>            } else {<br>                if nums[j] == minK {<br>                    minK_pos = j as i64;<br>                }<br><br>                if nums[j] == maxK {<br>                    maxK_pos = j as i64;<br>                }<br><br>                if minK_pos != -1 &amp;&amp; maxK_pos != -1 {<br>                    res += min(minK_pos, maxK_pos) - invalid_pos;<br>                }<br>            }<br><br>            j += 1;<br>        }<br><br>        res<br>    }<br>}</pre><h3>Chapter 5 — What only matters is whether it is greater or lesser than K.</h3><p><a href="https://leetcode.com/problems/count-subarrays-with-median-k/">2488. Count Subarrays With Median K</a></p><p>To solve this problem, we need several concepts, just like all the problems above, which I would go over. Most hard problems are hard because they involve multiple steps. This is true here, too.</p><p>The first concept that we need to understand is the median element, which is the element that comes just in the middle for odd-sized arrays, and in this problem, for even-sized arrays, we are supposed to take a left-middle element. So what matters is to see if K is in the middle or left-middle of our subarray; if it is, then it is a valid subarray, which we need to consider.</p><p>So, we can change the input into elements that are lesser than K with -1, K with 0, and then elements greater than K with 1. We will see why this change makes sense in the 2nd concept; let&#39;s do that for now.</p><pre>input = [3,2,1,4,5]<br>K = 4<br><br>After the transformation:<br>input = [-1, -1, -1, 0, 1]<br><br>We can see that our subarrays are going to be:<br>[0]<br>[0, 1]<br>[-1, 0, 1]</pre><p>Great, now we can also see that if we add up the elements of the valid subarrays, it comes between [0, 1]. More precisely, the sum is 0 for an odd-sized subarray, while for an even-sized subarray, it&#39;s 1.</p><p>But before we proceed further, let us solve another problem: Count all subarrays that sum up to 0 from the given array.</p><pre>input = [-1, -1, -1, 0, 1]<br><br>To solve this, we can use prefix sum array. Which is to calculate the cumulative<br>sums by elements.<br><br>prefix_sum_array = [0, -1, -2, -3, -3, -2]<br><br>The way to calculate the prefix_sum_array is to start with 0, then add:<br>  <br>      prefix_sum_array[i + 1] = prefix_sum_array[i] + input[i]<br><br>Now to calculate the sum of a subarray i to j, we need to use:<br>  <br>      sum_of_subarray_i_to_j = prefix_sum_array[j + 1] - prefix_sum_array[i]<br><br>So lets say we want to find the sum of subarray of elements from index 2 to 4, we would:<br>      <br>      sum_of_subarray_2_to_4 = prefix_sum_array[4 + 1] - prefix_sum_array[2]<br>                             = -2 - (-2)<br>                             = 0<br>      So we can check with the input array that indeed its 0: sum([-1, 0, 1])<br></pre><p>So now that we understand the concept of prefix_sum_arrays, how do we use this to solve the new problem: Count all subarrays that sum up to 0 from the given array?</p><pre>/**<br>To solve this problem what we need to so is for some index = j, we need to find<br>some index = i that when substracted gives us 0 as the result. More precisely,<br>we need to find some i which has the same value as the index j.<br><br>Here is the sudo code on how to do this:<br>**/<br><br>fn countOfSubarraysWithSumZero(input: Vec&lt;i32&gt;) {<br>  let mut prefix_sum_arrays = [0; input.len() + 1];<br>  <br>  let (mut j, mut prev_hashmap, mut res) = (1usize, HashMap::&lt;usize, usize&gt;::new(), 0usize);<br>  prev_hashmap.insert(0, 1);<br><br>  while j &lt; prefix_sum_arrays.len() {<br>      let key_j = prefix_sum_arrays[j] as usize;<br>      if prev_hashmap.contains_key(&amp;key_j) {<br>          res += *prev_hashmap.get(&amp;key_j).unwrap();<br>      } else {<br>          prev_hashmap.insert(key_j, 0);<br>      }<br>      prev_hashmap.insert(key_j, *prev_hashmap.get(&amp;key_j).unwrap() + 1);<br>  }<br>  <br>  res<br>}<br></pre><p>So, we have solved this, and isn’t this similar to the problem we have above the original problem? Find all subarrays that have sum = 0 or 1. So, let&#39;s continue the original problem.</p><pre>input = [3,2,1,4,5]<br>K = 4<br><br>After the transformation:<br>  input = [-1, -1, -1, 0, 1]<br><br>We can see that our subarrays are going to be:<br>  [0]<br>  [0, 1]<br>  [-1, 0, 1]<br><br>Lets now calculate the prefix_sum_arrays:<br>  prefix_sum_arrays = [0, -1, -2, -3, -3, -2]<br><br>Now, lets try to find all the subarrays that sum up to 0 or 1:<br><br>result = 0<br><br>-----------------------------------------<br>j = 1<br>hashmap = {0: 1}<br>current_sum = prefix_sum_arrays[1] = -1<br>To sum up to 0, we need to find -1 because <br>      prefix_sum_array[j + 1] - prefix_sum_array[i] = 0<br>   =&gt; prefix_sum_array[i] = prefix_sum_array[j + 1]<br><br>And To sum up to 1, we need to find -2 because<br>      prefix_sum_array[j + 1] - prefix_sum_array[i] = 1<br>   =&gt; prefix_sum_array[i] = prefix_sum_array[j + 1] - 1<br><br>We did not find either, so lets just add the -1 in the hashmap and continue.<br><br>result = 0<br><br>-----------------------------------------<br>j = 2<br>hashmap = {0: 1, -1: 1}<br>current_sum = prefix_sum_arrays[2] = -2<br><br>We need -2 or -3 in the hashmap, we didn&#39;t find it in the hashmap so we add the<br>current element -2 and move on.<br><br>result = 0<br><br>-----------------------------------------<br>j = 3<br>hashmap = {0: 1, -1: 1, -2: 1}<br>current_sum = prefix_sum_arrays[3] = -3<br><br>We need -3 or -4 in the hashmap, we didn&#39;t find it in the hashmap so we add the<br>current element -3 and move on.<br><br>result = 0<br><br>-----------------------------------------<br>j = 4<br>hashmap = {0: 1, -1: 1, -2: 1, -3: 1}<br>current_sum = prefix_sum_arrays[4] = -3<br><br>We need -3 or -4 in the hashmap, we finally found -3 in the hashmap,<br>we add the number of times we found -3 which 1 to the result.<br><br>result = 1<br><br>This is where things differ a bit, we don&#39;t add -3 again, as we have found a match.<br><br>-----------------------------------------<br>j = 5<br>hashmap = {0: 1, -1: 1, -2: 1, -3: 1}<br>current_sum = prefix_sum_arrays[5] = -2<br><br>We need -2 or -3 in the hashmap, we have both in the hashmap, we add the<br>number of times we saw both.<br>  result += hashmap[-2] + hashmap[-3]<br><br>result = 3<br>  <br>So finally our result is 3. Which is what we showed above, the subarrays will:<br>  [0]<br>  [0, 1]<br>  [-1, 0, 1]<br>Which translates to the original array as:<br>  [4]<br>  [4, 5]<br>  [1, 4, 5]</pre><p>Now, there is a small caveat in this solution: there can be cases where we get the same element or we element — 1 in the hashmap, but we did not include any element with K as the value. In our current example, by chance, we got the value 0 in the transformed array, k=4 in the original array, when we found j = 4 and j = 5. So how can we avoid this situation?</p><p>We can only start considering matches if the index (our j) is at the index where we have the element = K or beyond that index. Here is the pseudo-code with the change:</p><pre>input = [3,2,1,4,5]<br>K = 4<br><br>After the transformation:<br>  input = [-1, -1, -1, 0, 1]<br><br>We can see that our subarrays are going to be:<br>  [0]<br>  [0, 1]<br>  [-1, 0, 1]<br><br>Lets now calculate the prefix_sum_arrays:<br>  prefix_sum_arrays = [0, -1, -2, -3, -3, -2]<br><br>Now, lets try to find all the subarrays that sum up to 0 or 1:<br><br>result = 0<br><br>-----------------------------------------<br>j = 1<br>hashmap = {0: 1}<br>current_sum = prefix_sum_arrays[1] = -1<br><br><br>Index is not equal to or greater than index = 4 in the prefix_sum_array, <br>so lets just add the -1 in the hashmap and continue.<br><br>result = 0<br><br>-----------------------------------------<br>j = 2<br>hashmap = {0: 1, -1: 1}<br>current_sum = prefix_sum_arrays[2] = -2<br><br>Index is not equal to or greater than index = 4 in the prefix_sum_array, <br>so lets just add the -2 in the hashmap and continue.<br><br>result = 0<br><br>-----------------------------------------<br>j = 3<br>hashmap = {0: 1, -1: 1, -2: 1}<br>current_sum = prefix_sum_arrays[3] = -3<br><br>Index is not equal to or greater than index = 4 in the prefix_sum_array, <br>so lets just add the -2 in the hashmap and continue.<br><br>result = 0<br><br>-----------------------------------------<br>j = 4<br>hashmap = {0: 1, -1: 1, -2: 1, -3: 1}<br>current_sum = prefix_sum_arrays[4] = -3<br><br>Now we are at index = 4, so we can compare.<br>We need -3 or -4 in the hashmap, we finally found -3 in the hashmap,<br>we add the number of times we found -3 which 1 to the result.<br><br>result = 1<br><br>This is where things differ a bit, we don&#39;t add -3 again, as we have found a match.<br><br>-----------------------------------------<br>j = 5<br>hashmap = {0: 1, -1: 1, -2: 1, -3: 1}<br>current_sum = prefix_sum_arrays[5] = -2<br><br>We need -2 or -3 in the hashmap, we have both in the hashmap, we add the<br>number of times we saw both.<br>  result += hashmap[-2] + hashmap[-3]<br><br>result = 3<br>  <br>So finally our result is 3. Which is what we showed above, the subarrays will:<br>  [0]<br>  [0, 1]<br>  [-1, 0, 1]<br>Which translates to the original array as:<br>  [4]<br>  [4, 5]<br>  [1, 4, 5]</pre><p>Now that will work! Let&#39;s get it coded.</p><pre>use std::collections::HashMap;<br><br>impl Solution {<br>    pub fn count_subarrays(nums: Vec&lt;i32&gt;, k: i32) -&gt; i32 {<br>        let n = nums.len();<br><br>        let mut new_nums = vec![0];<br>        new_nums.resize(n, 0);<br><br>        for i in 0..n {<br>            if nums[i] &lt; k {<br>                new_nums[i] = -1;<br>            }<br>            else if nums[i] &gt; k {<br>                new_nums[i] = 1;<br>            } else {<br>                new_nums[i] = 0;<br>            }<br>        }<br><br>        let mut prefix_sum_arrays = vec![0];<br>        prefix_sum_arrays.resize(n + 1, 0);<br><br>        let mut index_where_zero = 0;<br>        for i in 0..n {<br>            prefix_sum_arrays[i + 1] = prefix_sum_arrays[i] + new_nums[i];<br>            if new_nums[i] == 0 {<br>                index_where_zero = i + 1;<br>            }<br>        }<br><br>        let (mut j, mut hashmap, mut res) = (1, HashMap::&lt;i32, i32&gt;::new(), 0);<br>        hashmap.insert(0, 1);<br><br>        while j &lt; prefix_sum_arrays.len() {<br>            let temp = prefix_sum_arrays[j] - 1;<br>            if j &gt;= index_where_zero {<br>                // Find 0<br>                if hashmap.contains_key(&amp;prefix_sum_arrays[j]) {<br>                    res += *hashmap.get(&amp;prefix_sum_arrays[j]).unwrap();<br>                }<br>                // Find 1<br>                if hashmap.contains_key(&amp;temp) {<br>                    res += *hashmap.get(&amp;temp).unwrap();<br>                }<br>            } else {<br>                let key = prefix_sum_arrays[j];<br>                if !hashmap.contains_key(&amp;key) {<br>                    hashmap.insert(key, 0);<br>                }<br>                hashmap.insert(key, *hashmap.get(&amp;key).unwrap() + 1);<br>            }<br>            j += 1;<br>        }<br>        res<br>    }<br>}</pre><h3>More things you might be interested in</h3><h4>Leetcoding in Rust</h4><ul><li><a href="https://daviddecoding.medium.com/leetcoding-in-rust-making-monotonic-stack-and-queue-easy-72105eee9970"><strong>Making Monotonic Stack and Queue Easy</strong></a></li></ul><h4>Coding</h4><ul><li><a href="https://medium.com/@daviddecoding/must-know-coding-and-problem-solving-concepts-to-ace-your-big-tech-interview-2f8745decd58"><strong>Must Know Coding and Problem-Solving Concepts to Ace Your Big Tech Interview</strong></a></li></ul><h4>System Design</h4><ul><li><a href="https://daviddecoding.medium.com/system-design-coding-it-up-f085a898a110"><strong>Big Tech Interview: Implementations of Alex Xu’s System Design Algorithms (Python) — Part 1</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c642461d79f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Must Know Coding and Problem-Solving Concepts to Ace Your Big Tech Interview]]></title>
            <link>https://daviddecoding.medium.com/must-know-coding-and-problem-solving-concepts-to-ace-your-big-tech-interview-2f8745decd58?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f8745decd58</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[meta]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 03:21:10 GMT</pubDate>
            <atom:updated>2024-06-28T01:00:43.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Zeh3KxqBtSi5B3EXjNTtsQ.jpeg" /><figcaption>Must Know Coding and Problem-Solving Concepts to Ace Your Big Tech Interview. Pic: From the Internet</figcaption></figure><p>Here is a guide without any fluff on preparing for your Coding and Problem-Solving Interviews for a FAANG (Meta, Apple, Amazon, Netflix, Google, Microsoft).</p><blockquote>In the beginnning, forget about the HARD questions in Leetcode (LC) if those do come up in the interview — Talk about your approach and ask for hints if you can’t proceed. But what you should do are as many EASY and MEDIUM questions in LC as you can per topic (given below). Then, read different problem statements and try to reason which algorithm best suits the problem.</blockquote><blockquote>Before you read the rest of the article, I wanted to point out the no. 1 reason why most people fail a coding test is because they can’t solve something that they think would be very easy to solve. e.g., Reversing a Linked List.</blockquote><h3>2D Matrix</h3><p>You have to flip the image, traverse the matrix in a spiral order, or something similar. These questions require you to maintain 4 pointers: left, right, top, and bottom. As you traverse from left to right, you increment the top by 1, then traverse from top to bottom, then decrement the right pointer by 1, then traverse from right to left, then decrement the bottom pointer by 1, then traverse from bottom to top, and finally increment the left pointer by 1, and repeat till there left is equal to or greater than right, and the top is equal to or greater than the bottom.</p><h3>Binary Search</h3><h4>2D Row and Column Sorted Matrix</h4><p>You are given a 2D Matrix, sorted by row and column in an increasing or decreasing manner. You need to find certain element/s using Binary Search. In most cases, you would start at the Bottom-Left or Top-Right, which is unusual, and then move in a staircase way up-right or down-left through the matrix.</p><h4>Median Finding</h4><p>In this problem, you must find the median of the merged array of 2 arrays. The technique is to run a binary search till you have split the 2 arrays in such that the merged array is split into equal halves. This requires some practice, where you use the array to run a binary search and then see if the conditions are being met before choosing the left or right halves.</p><h3>Monotonic Stack</h3><p>You maintain a stack that contains elements in increasing or decreasing order, thus called a monotonically increasing or decreasing stack. The elements are pushed into the stack by first comparing, and if the element meets the criteria (should be greater or lesser), it is pushed on top of the existing element in the stack. If it doesn’t meet the criteria, the top element is popped off, and the new element is pushed on top of the stack. The problems generally require you to find the next highest or lowest in a list of numbers and do this for each number.</p><p>The problems where you have an array of elements, and as you iterate through the elements, you need to keep track of the minimum or the maximum, and once you find the minimum or maximum, you discard all elements that have come before till you find something that is smaller than the minimum or larger than the maximum should hint you to use a Monotonic Stack.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaX1F2-DrBkQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaX1F2-DrBkQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaX1F2-DrBkQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/96e813a171f1a84d68a8bf2dddb9a9f4/href">https://medium.com/media/96e813a171f1a84d68a8bf2dddb9a9f4/href</a></iframe><p>A very interesting problem that uses a Monotonically Increasing Stack with other data structures and is very common in the interviews is the Remove Duplicate Letters problem, where we need to find a lexicographically smallest sequence that contains all letters in the string by removing letters.</p><h3>Monotonic Queue using Deque</h3><p>It is generally rare to see a problem that requires a Monotonic Queue, or rather I should say it won&#39;t be easy to come up with a solution that involves a Monotonic Queue. Still, this data structure do exist and one of the most interesting question regarding this data structure is Jump Game IV. The way this data structure works is that you always compare the current element with the element on the top of the queue, while you add data from the end of the queue.</p><h3>Quick Select</h3><p>This algorithm aims to find what element would go at a particular position and uses a very similar approach to Quick Sort. You start with 2 pointers, left and right, and then partition the list by a particular pivot value chosen from the list and then finally put the pivot element at the position where all elements to its left are smaller than itself, and all elements to the right are greater than itself.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXEmy13g1Qxc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXEmy13g1Qxc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXEmy13g1Qxc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/730ebd4490cb0ec21f89e07c4544f19b/href">https://medium.com/media/730ebd4490cb0ec21f89e07c4544f19b/href</a></iframe><h3>Prefix Sum</h3><p>You create another array that calculates the cumulative sum as you move from the beginning to the end of the original array. Using this new array, you can solve several sub-array problems.</p><h4>1D Vectors</h4><p>As the name suggests, an array of integers are given, and to solve the problem, you need to create another array with their prefix sums.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPhgtNY_-CiY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPhgtNY_-CiY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPhgtNY_-CiY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/98ac222858bf591ce4ef206f51a755a5/href">https://medium.com/media/98ac222858bf591ce4ef206f51a755a5/href</a></iframe><h4>2D Matrix</h4><p>This is complex as you create the prefix sum of a 2D Matrix by walking down each element in the 2D Matrix by calculating the running sum by columns in the row and adding the prefix sum of the previous row. To get the range sum, you take the Prefix sum of the right bottom, then subtract the prefix sum of the top rows, then subtract the prefix sum of the left columns, and then finally add back the Prefix sum of the top left.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKE8MQuwE2yA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKE8MQuwE2yA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKE8MQuwE2yA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/873ea2e2b2c558b7588669968cda1b4c/href">https://medium.com/media/873ea2e2b2c558b7588669968cda1b4c/href</a></iframe><h3>Two Pointer Techniques</h3><h4><strong>Lead-Lag pointers</strong></h4><p>You have two pointers, most likely pointing to 2 separate nodes in a list so that you can keep track of nodes separated by a distance. e.g., <strong><em>current</em></strong> and <strong><em>previous</em></strong> pointers help reverse the Linked List (LL).</p><h4><strong>Fast-Slow pointers</strong></h4><p>You have two pointers, most likely starting from the same node, but one moves faster than the other as you change them. e.g., <strong><em>fast</em></strong> and <strong><em>slow</em></strong> pointer, which points to the same head node, but <strong><em>fast</em></strong> moves two times faster than the <strong><em>slow</em></strong> pointer, which is handy if you want to find the middle node of the LL or detect cycles.</p><blockquote><strong>One of the best article I have found to learn the concept:<em> <br></em></strong><a href="https://towardsdatascience.com/two-pointer-approach-python-code-f3986b602640">https://towardsdatascience.com/two-pointer-approach-python-code-f3986b602640</a></blockquote><h4>Left-Right pointers — Greedy</h4><p>You set two pointers, a left pointer at the beginning and a right pointer at the end of a list, and calculate the max or min, and then, based on the problem, you increase the left pointer or decrease the right pointer to find the max or min.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUuiTKBwPgAo&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUuiTKBwPgAo&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FUuiTKBwPgAo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e67db93bd55a85f6b4ae67863237367/href">https://medium.com/media/2e67db93bd55a85f6b4ae67863237367/href</a></iframe><h3>Sliding Window Techniques</h3><p>These problems involve finding some or counting all subarrays/substrings. Subarrays/Substrings: These are contiguous and ordered chunks of elements from an array/string.</p><h4>Fixed Sliding Window</h4><p>In these types of problems, we take a fixed-sized window generally provided to us in the problem itself and move the window one element at a time. The optimization we do, as we move the window by one element, is that we compute the difference in the result by dropping the last element of the previous position sliding window contained and then adding in the new element that the new position sliding window will contain.</p><h4>Dynamic Sliding Window</h4><blockquote><strong><em>Note:</em></strong><em> </em>This is one of the most trickiest types of problem. It can range from finding a valid solution to collecting all valid solutions (when the end goal is met by expanding and/or shrinking the window). You need a lot of practicing to get a decent understanding of these problems.</blockquote><p>In these types of problems, the window size is not fixed, and we either expand the window or shrink the window based on some criteria given in the problem. We do a very similar optimization as the Fixed Size Window problem; we drop the last element of the previously sized window when we shrink the window or add the new element that gets added when we expand the window.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjM2dhDPYMQM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjM2dhDPYMQM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjM2dhDPYMQM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d27fa2d1ec199533c224459199857944/href">https://medium.com/media/d27fa2d1ec199533c224459199857944/href</a></iframe><h4>Kadane’s Algorithm</h4><blockquote><strong><em>Note:</em></strong><em> </em>There are problems that can take both Kadane’s Algorithm and Dynamic Sliding Window together. These are generally HARD problems, don’t expect these to just come up. Most likely just applying Kadane’s Algorithm will come up which can be solved by using Dynamic Programming (DP) too.</blockquote><p>This is a special type of Dynamic Sliding Window, which breaks the rule that expanding the window should only take the value we are searching for in a single direction, i.e., positive or negative. This generally applies when we have both negative and positive numbers in a list, and we have to find a subarray with something like the desired sum. You keep a global maximum (or minimum) sum and the current maximum (or minimum) sum. Then, for each element, you take just the element or the current maximum with the element and set the current maximum to the max of these two values. Similarly, you compare the new current maximum with the global maximum and set it accordingly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4csAswCkXZM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4csAswCkXZM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4csAswCkXZM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/357103addd544236aebcd326600671ea/href">https://medium.com/media/357103addd544236aebcd326600671ea/href</a></iframe><h4>Maximum Sum of Subarrays ending at each Index</h4><p>When applying just Kadane’s algorithm, we get the sum of the Maximum Sum of Subarrays ending at each index, and then we take a maximum on all these sums to get the Maximum Sum of Subarrays. But we can also store the Maximum Sums of Subarrays that end at each index so that we can use them to solve problems like the Maximum Sum of Subarrays with at least K elements. In this case, you take the sum of K elements from each Index of the Array and then add the Maximum Sum of Subarrays for the Index previous to this to get the Maximum Sum of Subarrays of K and above elements.</p><h3>Backtracking</h3><p>These problems generally involve finding some or counting all subsets from an array/string. Subsets: These are arrays/strings that can be formed by taking all or some elements from another array/string. They don’t have to be contiguous/ordered.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIEIuLXZSjtY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIEIuLXZSjtY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIEIuLXZSjtY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eba039ed951d26f7157bb5a0282bc623/href">https://medium.com/media/eba039ed951d26f7157bb5a0282bc623/href</a></iframe><h4>Combinations</h4><p>In these types of problems, you either select the current element and then select or not select elements that come after it in a list. Generally, we also sort the list by some criteria before selecting and not selecting elements.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3yshETDtQhI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3yshETDtQhI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3yshETDtQhI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/720353ba53d62776e4951f23a08d55ea/href">https://medium.com/media/720353ba53d62776e4951f23a08d55ea/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdF-BYlzV3Yk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdF-BYlzV3Yk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdF-BYlzV3Yk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d46168cca75ad4f8b72b34f74c137c5c/href">https://medium.com/media/d46168cca75ad4f8b72b34f74c137c5c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fap7Bzj9MLkU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dap7Bzj9MLkU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fap7Bzj9MLkU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1960dde01e4b57c772471a066f7c70c1/href">https://medium.com/media/1960dde01e4b57c772471a066f7c70c1/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fgw85sDhe6l4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dgw85sDhe6l4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fgw85sDhe6l4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0fec0085edfb466ea83353e8d48cf22/href">https://medium.com/media/a0fec0085edfb466ea83353e8d48cf22/href</a></iframe><h4>Permutations</h4><p>In these types of problems, we would select all elements differently. So, in a list, we select the first, then the second, and finally the third, or we might first select the second, then the first, and finally the third.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FO5HESouH6RY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DO5HESouH6RY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FO5HESouH6RY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5974a9801cc3698763c8ce3072890cd6/href">https://medium.com/media/5974a9801cc3698763c8ce3072890cd6/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FD6zucvsR2Tg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD6zucvsR2Tg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD6zucvsR2Tg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2a6e621e9826f0f9f86df1cd00a7961/href">https://medium.com/media/a2a6e621e9826f0f9f86df1cd00a7961/href</a></iframe><h4>Subsets</h4><p>In these types of problems, we collect the result as we select or do not select the current element and the elements after that. These are similar to combination problems but where the resulting elements are collected as we try the next element.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFy7p4ADLwow%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFy7p4ADLwow&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFy7p4ADLwow%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/68c3d38c13ca7d910240ba5923f54f7c/href">https://medium.com/media/68c3d38c13ca7d910240ba5923f54f7c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fgz5Ui2csabU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dgz5Ui2csabU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fgz5Ui2csabU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed2ab935d3701a95d9628184bf17bfc0/href">https://medium.com/media/ed2ab935d3701a95d9628184bf17bfc0/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTG9Qymgw5BY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTG9Qymgw5BY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTG9Qymgw5BY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/514b1ac794838f7717bd6b6436dcda77/href">https://medium.com/media/514b1ac794838f7717bd6b6436dcda77/href</a></iframe><h3>Graph</h3><h4><strong>Depth-First Search</strong></h4><p>You have a function that recursively calls itself with the next node; this is important to solve many from LL, Trees, and Graphs.</p><h4>Breadth-First Search</h4><p>You have to find the shortest path in an unweighted graph. You need a queue to store the following children to process.</p><h4>Spanning Tree</h4><p>Two separate algorithms use different data structures to find the minimum spanning tree. Prim starts from a node, adds the adjacent nodes in a min-heap, and takes the less weighted edge node. Kruskal requires a union-find and sorting the edges by weight, then keeping the nodes&#39; union.</p><h4>Shortest Path</h4><p>This uses Dijkstra’s algorithm to solve problems where you must find the shortest path. You start from the starting node, drop edges in a min-heap, and select the less weighted edges till the final node is processed.</p><h4>Post-Order DFS — Topological Sorting</h4><p>This differs for Directed and Undirected graphs. In the case of Undirected graphs, you maintain a visited array, and as you run a DFS and run into a node already marked visited in the visited array, it has a cycle. In the case of a Directed graph, you need to do backtracking on top of the algorithm for an Undirected graph, which means you need to keep a visited and pathVisited array and keep marking both as you run the DFS. Still, in the post-order, you need to unmark the pathVisited array, and in case you run into a node with both visited and pathVisited array marked as visited for the node, then it has a cycle.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9twcmtQj4DU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9twcmtQj4DU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9twcmtQj4DU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdc836cd76b9c4b37c4fb9d1ce9f3470/href">https://medium.com/media/cdc836cd76b9c4b37c4fb9d1ce9f3470/href</a></iframe><h4>Kahn’s Algorithm — Topological Sorting</h4><p>This uses Kahn’s algorithm to find the topological ordering of dependencies. Here, you calculate the indegrees and create the adjacency list-based graph. Then you put the nodes with 0 indegrees in a queue and keep removing the indegrees and adding the nodes with 0 indegrees in the queue. This only works in a DAG (Directed Acyclic Graph).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcIBFEhD77b4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcIBFEhD77b4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcIBFEhD77b4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bb839d8c2953c61d5f8e3749e30c0aa/href">https://medium.com/media/6bb839d8c2953c61d5f8e3749e30c0aa/href</a></iframe><h4>Union Find</h4><p>This special data structure helps with Spanning Tree, Connected components related to graph problems. You track each node&#39;s parent and rank as you union them, and while doing a find operation, you do path compression.</p><h3>BST</h3><p>This is a particular type of graph, so everything in the graph section can be performed here, too. But the way it is structured, there are some exciting things you can do with BSTs that are impossible with any generic graph.</p><h4>Binary Traversal</h4><p>You traverse the tree with DFS by going down the left or the right node to calculate the result. This can solve problems like range sum, searching for an element, searching for the closest element, etc.</p><h4>In-order Traversal</h4><p>You traverse the tree with DFS by processing the left node, the current node, and finally, the right node. This can solve an interesting problem where you want to read the elements in increasing or decreasing sorted order without even sorting the tree.</p><h4>Post-order Traversal</h4><p>You will traverse the tree with DFS but will process the left and right nodes and most likely use their results to process the current node. This is very useful to solve problems like validating the BST.</p><h4>Level-order Traversal</h4><p>You will traverse the tree by levels; in this case, you would do a BFS with 2 separate queues. First, you would go through the 1st queue; then, for each unexplored child, you would drop it in the previous queue. Once you finish the 1st queue, you will copy over all the elements from the 2nd queue to the 1st queue and keep going. Every time you copy over the elements, you will be processing the tree by levels.</p><h4>Vertical-order Traversal</h4><p>You will traverse the tree by each level, where you consider vertical lines marking the root with (0, 0), while its left will be (-1, 1) and right (1, 1), and their children will be (-2, 2), (-1, 2) and (1, 2), (2, 2) respectively. This will help you solve several problems like top-level, right/left, vertical order views of the binary tree, etc.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fq_a6lpbKJdw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dq_a6lpbKJdw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fq_a6lpbKJdw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bb89f48ca4d4d82a9567e9789024897/href">https://medium.com/media/1bb89f48ca4d4d82a9567e9789024897/href</a></iframe><h4>Reverse Level/Vertical Order</h4><p>This is one of the most exciting traversal as it is the reverse of Level/Vertical Order where rather than sending tuples of information down to the children and processing it at the children, you get data from the two children and process it in the parent. This can be elements you were searching for in the tree, the min and max values, or getting the costs of taking a path like in problems - Lowest Common Ancestor, Validating a Binary Search Tree, Making Costs of Paths Equal in a Binary Tree respectively.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_-QHfMDde90%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_-QHfMDde90&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_-QHfMDde90%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddb1f1a2d42ff511a4877babbfbf5c9/href">https://medium.com/media/4ddb1f1a2d42ff511a4877babbfbf5c9/href</a></iframe><h4>Predecessor and Successor Nodes</h4><p>You can find the predecessor of a node by running a DFS from the left child and only taking the right children from there on. The last right child will be the predecessor. Similarly, if you run a DFS from the right child and only take the left children from there on. The last left child will be the successor.</p><h4>Count Nodes by Height</h4><p>This is another exciting pattern where you calculate things on the left and the right with O(log n). Then, if it doesn’t meet the criteria, you repeat this process for the left and right nodes, i.e., again calculate the things on the left and right with O(log n) and send back the result up through the recursion. The best way to understand this is to count complete tree nodes; the most optimal solution is O(log n * log n).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fu-yWemKGWO0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Du-yWemKGWO0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fu-yWemKGWO0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/084075fc1327e24a41929bf4e21d6a1c/href">https://medium.com/media/084075fc1327e24a41929bf4e21d6a1c/href</a></iframe><h4>Reverse PostOrder Traversal</h4><p>This is another exciting way to solve a few problems, where you have to traverse the right node first, then the left node, and finally the original node. This is used in the problem Flatten a Binary Tree into a Linked List. The other thing to note in the problem is to keep track of the last node we saw so that it can be modified as we traverse through the tree.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsWf7k1x9XR4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsWf7k1x9XR4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsWf7k1x9XR4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/32548baa457b60135f15c7a63c9553a8/href">https://medium.com/media/32548baa457b60135f15c7a63c9553a8/href</a></iframe><h3>Trie</h3><p>You can represent any array of elements in this unique structure called the Trie. It is a particular type of tree where each node contains a list of pointers to the following nodes.</p><h4>Integer Trie</h4><p>An integer can be converted to its binary representation and stored in a Trie. This will help with any bitwise operation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEIhAwfHubE8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEIhAwfHubE8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEIhAwfHubE8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d0fdd9238a2b7839b1dca24df64160e/href">https://medium.com/media/2d0fdd9238a2b7839b1dca24df64160e/href</a></iframe><h3>Dynamic Programming (DP)</h3><p>These have already been categorized by Neetcode here: <a href="https://docs.google.com/spreadsheets/d/1pEzcVLdj7T4fv5mrNhsOvffBnsUH07GZk7c2jD-adE0/edit#gid=0">https://docs.google.com/spreadsheets/d/1pEzcVLdj7T4fv5mrNhsOvffBnsUH07GZk7c2jD-adE0</a>. I will still add them here just for completeness.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FmBNrRy2_hVs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DmBNrRy2_hVs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FmBNrRy2_hVs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/953aa353acd75d969a51d3e0b6acfdd9/href">https://medium.com/media/953aa353acd75d969a51d3e0b6acfdd9/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzDEQaDl3cso%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzDEQaDl3cso&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzDEQaDl3cso%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c3e33d350f0f0f3fc762eda7b4de77/href">https://medium.com/media/d4c3e33d350f0f0f3fc762eda7b4de77/href</a></iframe><h4>Misc</h4><p>These are problems that are generally 1D or Constant Space DP problems where the last few results are kept to calculate the next result. Classic Examples are Fibonacci Numbers, Climbing Stairs, etc.</p><h4>1/0 Knapsack or Take or Not Take</h4><p>These are problems where you are given a list and try to calculate the result by taking only one element in each iteration or skipping the element from the list.</p><h4>Unbounded Knapsack</h4><p>These are problems where you are given a list, but unlike 1/0 Knapsack, you can take an element as often as you would like or skip it. This technique can also be used to choose elements that will sum up to half the sum of the array.</p><h4>Subsequences</h4><p>These are problems where you take elements like 1/0 Knapsack but from 2 separate lists to achieve a goal.</p><h4>Palindromes</h4><p>These are different from typical DP problems as there is no space requirement in general, but you need a trick where you take each element as the center of a possible palindromic string or subsequence and achieve the goal.</p><h3>Greedy</h3><blockquote><strong><em>Note:</em></strong> This is the most trickiest of all algorithms. Some of the problems will make your brain melt, so hope that your interviewer doesn’t want to make you bleed and asks some brain-melting greedy optimizable problem. Do the brute force if you can, curse your interviewer in the back of your mind, and move on.</blockquote><p>This is the most important and interesting topic, as a few problems can be solved using a Greedy approach. You need to know the types of problems that fit into this paradigm.</p><h4>Intervals — Sort by start time</h4><p>In these problems, you are trying to take only some elements by merging them. This technique is very useful in solving Interval Graph Coloring problems, where you must color/associate rooms to accommodate different intervals.</p><h4>Intervals — Sort by asc end time, and then desc start time</h4><p>In these types of problems, you try to avoid as many conflicts as possible. You sort by the end time and take the smallest if there is a tie. Then, take the sum of the non-overlapping intervals.</p><h4>Intervals — Sort start times and end times separately</h4><p>In these types of problems, you take two separate arrays and add all the start and end times. Then, you sort the arrays in non-decreasing order to process.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFdzJmTCVyJU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFdzJmTCVyJU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFdzJmTCVyJU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2d9aac69e18997f2da1f83f2ddf3fd8/href">https://medium.com/media/f2d9aac69e18997f2da1f83f2ddf3fd8/href</a></iframe><blockquote><strong>One of the best article I have found to learn this concept:</strong> <br><a href="https://mecha-mind.medium.com/algo-pattern-recognition-interval-and-scheduling-problems-184df33f7cf1">https://mecha-mind.medium.com/algo-pattern-recognition-interval-and-scheduling-problems-184df33f7cf1</a></blockquote><h4>Sorting both Increasing and Decreasing Order</h4><p>Generally, Greedy problems require either sorting or counting. For sorting problems, you sort the input array and then pick elements as required. But a special type of problem is where you are given an array of tuples of 2 integers and need to find the optimal solution. As in the problem, <a href="https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/">The Number of Weak Characters in the Game</a>, you will need to first sort the array in ascending order by the first integer in the tuple, then you need to sort the array in decreasing order by the second integer in the tuple for the optimal solution.</p><h3>Segment Trees</h3><p>You store the elements of an array into a binary tree, where it takes log n time to query or update the values and maintain their sum or anything else you would like to query for. This is very useful for problems like range queries.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2FShdqn-Oz8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2FShdqn-Oz8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2FShdqn-Oz8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaeecd6c0d6827c17317a1b215646455/href">https://medium.com/media/eaeecd6c0d6827c17317a1b215646455/href</a></iframe><h3>Binary Maths</h3><p>These problems require some understanding of Bit Manipulation. Most importantly, you need to understand XOR.</p><h4>Bit Masking</h4><p>You must create a mask and then apply and/or operator to set or clear a bit.</p><h4>Integer to Binary</h4><p>You keep dividing the number by 2; the reminders will make up the digits in binary representation.</p><h4>XOR</h4><p>There are specific properties you need to know about this fascinating operator.</p><ol><li>The XOR of 2 same number is 0. e.g. 1 ^ 1 = 0, 8 ^ 8 = 0.</li><li>The XOR of any number with 0 is the same number. e.g. 1 ^ 0 = 1, 8 ^ 0 = 8.</li><li>The maximum result of XOR of any number with a number from a range of 1…n will equal the number XOR with the maximum value in the range 1…n. e.g. max(8 ^ [1…n]) = 8 ^ n</li></ol><p>One of the most interesting problems using XOR is <a href="https://leetcode.com/problems/single-number-iii/description/">Single Number III</a>. This requires not only the knowledge of XORing numbers to remove duplicates, but if the 2 numbers differ by 2 bits, then bucketing all numbers into 2 separate buckets having that particular bit set or not set and then XORing them would actually give you the resulting numbers. This can also be generalized to as many numbers there are. Find the differing bits, group numbers having the differing bits recursively, and then XOR all numbers in each buckets.</p><h3>More things you might be interested in</h3><h4>System Design</h4><ul><li><a href="https://daviddecoding.medium.com/system-design-coding-it-up-f085a898a110"><strong>Big Tech Interview: Implementations of Alex Xu’s System Design Algorithms (Python) — Part 1</strong></a></li></ul><h4>Coding Interview</h4><ul><li><a href="https://daviddecoding.medium.com/leetcode-problems-you-must-know-429dfae5502d"><strong>Leetcode Problems You Must Know</strong></a></li></ul><h4>Low Level Programming</h4><ul><li><a href="https://daviddecoding.medium.com/know-your-bits-and-bytes-406942418c05">Know your Bits and Bytes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f8745decd58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Engineering Vs. Life]]></title>
            <link>https://daviddecoding.medium.com/software-engineering-vs-life-e283f0451c26?source=rss-1c6e1f5644e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e283f0451c26</guid>
            <category><![CDATA[software-engineer-life]]></category>
            <category><![CDATA[mindfulness-at-work]]></category>
            <category><![CDATA[senior-software-engineer]]></category>
            <dc:creator><![CDATA[David De]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 07:21:38 GMT</pubDate>
            <atom:updated>2023-12-08T11:40:30.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*uhdocRp6OAZnYQG7hCIpAQ.png" /><figcaption>Working on his code, while life calls — Software Engineering Vs. Life</figcaption></figure><p>The principles that guide life often directly conflict with the principles of Software Engineering. I am not saying that all principles are head-butting each other, but some fundamental ones conflict a lot. A disclaimer: You might disagree with me on some Life or Software Engineering principles, but that is also a fine lesson in Life.</p><h3>Life is more art than science</h3><p>Software Engineering is based on science and its limitations, even though you can be creative within the boundaries of these limitations. But you must do more than go your separate ways to build software. It’s a discipline that takes time to master. You must build on top of what has come before or within the boundaries set by your team, company, funding, or technology.</p><p>Life is more art than science. Following the best practices laid down by someone will rarely get you the best results. Being mindful yet curious will take you the farthest. You can desire anything, act on it, accept the consequences, and desire it again. You can outgrow your desire and find a new one. As your circumstances and context will be different than anyone else, your actions will be quite different, too, even if the desire is the same. Your life is unique, and no one can replace your life; your series of actions and their consequences will also be unique.</p><h3>Life is about discovery</h3><p>Software Engineering needs a certain level of certainty. You need to plan and act according to the plan, and sometimes, you might have to have a plan for the plan in case things don’t go according to the plan. For example, at Amazon, we would run load tests and several other tests with traffic at the levels the Tech Ops team thought we would get based on several heuristics. Now, even if we came back green, i.e., we passed all the tests, we still had to present a list of things that could go wrong and what we could do to fix these; as an example, let’s say we are running into performance issue for one of our services, could we then pull a lever and shutdown some non-critical functionality so that we can alleviate the issue or get to a graceful degradation of service.</p><p>Life, on the other hand, is anything but living by a plan. You will constantly face challenges requiring you to use your experience or learn on the fly to overcome them. That is what makes life beautiful. Sure, you might need some security now and then, but too much of it and you have created a life not worth living anymore. Planning your life away is throwing your life away. Yes, you need desires to act on them, to find out if they work. And then outgrow them and have new desires. But don’t confuse desires with goals; machines, processes, and systems have goals, and a living, thinking being has desires.</p><h3>Life gets easier with time</h3><p>Software Engineering gets complex with time. You need to constantly learn new things as new approaches, from new languages to new technologies, arise. And with experience, you gain trust; with it, the stakes get higher and higher, and the room to make mistakes gets smaller and comes with larger consequences with every mistake.</p><p>Life is just the opposite. It gets simple: you know what you like to eat, what you like to do for recreation, what kind of people you like to keep around. You start asking the right questions and learn to listen to yourself for answers. With trust, it becomes easier to get new opportunities to get into groups you always desired to be part of, and you build a network of like-minded individuals who keep you motivated and desire things that were out of reach before.</p><h3>Goals in life evolve</h3><p>The goals of Software Engineering rarely evolve. It’s the same non-functional requirements you try to optimize with newer, better tools year after year. There is a saying that if you squint hard enough, you will see the same thing being done with the same constraints in 2 separate systems used for completely different purposes. The overall goal of what the system was supposed to do might evolve. In that case, you build another system that, in many senses, will look and feel similar to what you have already done.</p><p>Life should not have goals; desires, yes, which you must have, or else it’s not worth living, but goals not really. God forbid you have SMART Goals for your life that are attainable, relevant, and time-bound. Why would you spend your entire life, or even part of it, on something attainable — when you know it’s attainable? If it’s attainable, then you need to think bigger. When you were small and desired a toy, did you plan according to what your parents could afford or when they would say yes? Or when you fell in love, did you think s/he was out of your league, so not worth pursuing? And desires are never relevant, or attaching a reason for the desire doesn’t make it more or less desirable. When you want something and truly desire it, you have to have it, not by committing a crime. Also, when you have a desire, you can only act on it; the results are not in your hands. You can constantly nag your parents for the toy, try to woo that girl or boy, or study for that exam. But when your desire is met, or will it even be, it is not in your hands in most cases.</p><h3>Conclusion</h3><p>Sometimes, we let our software engineering selves run our lives, too. We look for best practices to live, plan for bad days, think our lives are getting worse, and want things we can achieve something meaningful immediately. I hope you found a new way to look at life, taking your eyes off your favorite IDE.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e283f0451c26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>