<?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 Dayita Chaudhuri on Medium]]></title>
        <description><![CDATA[Stories by Dayita Chaudhuri on Medium]]></description>
        <link>https://medium.com/@dayita.chaudhuri?source=rss-a334f21539c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HfjKYq2bMAVr_emtmUPKjg.png</url>
            <title>Stories by Dayita Chaudhuri on Medium</title>
            <link>https://medium.com/@dayita.chaudhuri?source=rss-a334f21539c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:10:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dayita.chaudhuri/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[Mountain Array Problems— Binary Search]]></title>
            <link>https://medium.com/@dayita.chaudhuri/mountain-array-problems-binary-search-69bb218ba7d3?source=rss-a334f21539c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/69bb218ba7d3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mountain-array]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[binary-search]]></category>
            <dc:creator><![CDATA[Dayita Chaudhuri]]></dc:creator>
            <pubDate>Sat, 06 Aug 2022 20:06:56 GMT</pubDate>
            <atom:updated>2022-08-11T05:02:00.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DENauUixUf2DS-VfgKCXlA.png" /></figure><p>Let us discuss the concepts in these questions —</p><p><strong>1. Monotonic Array:</strong></p><p>Array that is either strictly non-decreasing or strictly non-increasing.</p><p>Examples include :</p><p>{ 1,2,3,4,5 } {9,8,7,6,5} {10,20,20,30}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*FP-vkxC5eOywjEft" /></figure><p><strong>2. Bitonic Array :</strong></p><p>Array that is first strictly increasing then after a point decreasing.</p><p>Example is : {1,2,3,4,3,2,}</p><p><strong>Peak :</strong></p><p>The peak of a bitonic array is the largest element of the array, before which the array is strictly increasing and after which the array is strictly decreasing. Here we need to find the peak of the given bitonic array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JH3McYoWBkoZZFea.jpg" /></figure><p>Before starting with Bitonic Array, let us see how to implement Binary Search in a Monotomic Array.</p><h3>704. Binary Search</h3><p>Difficulty — Easy</p><p>Link — <a href="https://leetcode.com/problems/binary-search/">https://leetcode.com/problems/binary-search/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*ZijmyBxVsCBCVyYiogTMzg.png" /></figure><blockquote><strong>Recursive Binary Search</strong></blockquote><pre>class Solution:<br>    def search(self, nums: List[int], target: int) -&gt; int:<br>        <br><strong>        def binsearch(nums, target, start, end):</strong></pre><pre>            if start&lt;end:<br>                mid=(start+end)//2<br>                if nums[mid]==target:<br>                    return mid<br>                elif nums[mid]&gt;target:<br>                    return <strong>binsearch(nums,target,start,mid-1)</strong><br>                else:<br>                    return <strong>binsearch(nums,target,mid+1,end)</strong><br>            return -1<br>        <br>        return binsearch(nums,target,0,len(nums)-1)</pre><blockquote><strong>Iterative Binary Search</strong></blockquote><pre>class Solution:<br>    def search(self, nums: List[int], target: int) -&gt; int:<br>        <br>        start, end = 0, len(nums)-1<br>        <br>        while start&lt;=end:<br>            mid=(start+end)//2<br>            if nums[mid]==target:<br>                <strong>return mid</strong><br>            elif nums[mid]&gt;target:<br>                <strong>end=mid-1</strong><br>            else:<br>                <strong>start=mid+1</strong><br>        <br>        return -1</pre><p>Time = O(log N) and Space = O(1)</p><p>Now we can move to Bitonic Arrays.</p><p><strong>Contents —</strong></p><ul><li>Valid Mountain Array</li><li>Peak Index in Mountain Array</li><li>Find in Mountain Array</li></ul><p>Before we start working on a Mountain Array, let us try to identify if an array is a mountain array.</p><h3>941. Valid Mountain Array</h3><p>Difficulty — Easy</p><p>Link — <a href="https://leetcode.com/problems/valid-mountain-array/">https://leetcode.com/problems/valid-mountain-array/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*F9jCZcVP6Wrf_2l7Dc6kKw.png" /></figure><blockquote><strong>Method 1 — Increasing and Decreasing Subarrays</strong></blockquote><p>In this method, we will keep count of number of increasing and decreasing elements.</p><ol><li>Use a flag to check if the array is currently increasing or decreasing. Use incr and decr to keep count of increasing and decreasing subarray length.</li><li>If length if less than 3, return False.</li><li>Using a for loop iterate all indices.</li><li>If index is at increasing slope: If flag=1 ie already decreased return False. Else increment incr.</li><li>If value at index is equal to the next value, return False.</li><li>If index is at decreasing slope: set flag=1 and increment decr.</li><li>If we come out of the loop with finite length of increasing and decreasing subarray, neither equal to 0, return True. Otherwise return False.</li></ol><pre>class Solution:<br>    def validMountainArray(self, arr: List[int]) -&gt; bool:<br>        <br>        flag, incr, decr = 0, 0, 0<br>        <br>        if len(arr)&lt;3:<br>            return False<br>        <br>        for i in range(0,len(arr)-1):<br>            <br>           <strong> # If increasing</strong><br>            if arr[i]&lt;arr[i+1]:<br>                if flag==1:<br>                    return False<br>                incr+=1<br>            <br>           <strong> # If equal</strong><br>            elif arr[i]==arr[i+1]:<br>                return False<br>            <br>           <strong> # If decreasing</strong><br>            else:<br>                flag=1<br>                decr+=1<br>        <br>        <strong># If there are zero increasing ot decreasing elements</strong><br>        if incr==0 or decr==0:<br>            return False<br>        <br>        return True</pre><p>Time = O(N) and Space = O(1)</p><blockquote><strong>Method 2 — Count of Number of Changes</strong></blockquote><p>In this method, unlike the last method, we will keep count of the number of changes.</p><ol><li>If the length of the array is less than 3 or the array is initially decreasing, return False.</li><li>Use variable change to keep count of the number of changes. Use a for loop to iterate from 1 to n-2.</li><li>If arr[i-1]==arr[i] or arr[i+1]==arr[i], return False.</li><li>If there is a change in relative greatness of arr[i-1] and arr[i+1] wrt arr[i], increment change.</li><li>If at any iteration, change exceeds 1, return False.</li><li>After coming out of the loop, if the number of changes is 1, return True. Else return False.</li></ol><pre>class Solution:<br>    def validMountainArray(self, arr: List[int]) -&gt; bool:<br>        <br>        change=0<br>        <br>        if len(arr)&lt;3:<br>            return False<br>        <br>        if arr[0]&gt;=arr[1]:<br>            return False<br>        <br>        for i in range(1,len(arr)-1):<br>            <br>         <strong>   # If Equal</strong><br>            if arr[i-1]==arr[i] or arr[i]==arr[i+1]:<br>                return False<br>            <br>           <strong> # Count Changes</strong><br>            if (arr[i-1]&gt;arr[i]) != (arr[i]&gt;arr[i+1]):<br>                change+=1</pre><pre>           <strong> # If changes exceed 1</strong><br>            if change&gt;1:<br>                return False<br>        <br>        if change==1:<br>            return True<br>        <br>        return False</pre><p>Time = O(N) and Space = O(1)</p><h3>852. Peak Index in a Mountain Array</h3><p>Difficulty — Medium</p><p>Link — <a href="https://leetcode.com/problems/peak-index-in-a-mountain-array/">https://leetcode.com/problems/peak-index-in-a-mountain-array/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*3DPRxmO1T1ToiVJirbo06w.png" /></figure><blockquote><strong>Binary Search</strong></blockquote><ol><li>If we encounter the peak, we return it.</li><li>If we fall upon slope up condition, we shift left boundary to mid+1.</li><li>If we fall upon slope down condition, we shift right boundary to mid-1.</li></ol><pre>class Solution:<br>    def peakIndexInMountainArray(self, arr: List[int]) -&gt; int:<br>        <br>        n=len(arr)<br>        l, r = 0, n-1<br>        <br>       <strong> # Binary Search </strong><br>        <br>        while l&lt;=r:<br>            <br>            mid=(l+r)//2<br>            <br>            <strong># If mid is peak</strong><br>            if mid!=0 and mid!=n-1 and arr[mid]&gt;arr[mid-1] and <br>            arr[mid]&gt;arr[mid+1]:<br>                return mid<br>            <br>           <strong> # If mid is in slope up</strong><br>            if mid==0 or (mid!=n-1 and arr[mid]&lt;arr[mid+1]):<br>                l=mid+1<br>            <br>            <strong># If mid is in slope down</strong><br>            else:<br>                r=mid-1</pre><p>Time = O(log N) and Space = O(1)</p><h3>162. Find Peak Element</h3><p>Difficulty — Medium</p><p>Link — <a href="https://leetcode.com/problems/find-peak-element/">https://leetcode.com/problems/find-peak-element/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*bWICxJkurLKcaVXua-rS2g.png" /></figure><p>The main difference between the last question and this one is at the edge cases, ie for indices 0 and n-1.</p><p>In the last question, indices 0 and n-1 cannot be the peaks as these are the edges. But in this question we consider arr[-1] and arr[n] to be -infinity, hence indices 0 and n-1 can be considered as peak.</p><p>The only difference will be in the peak condition.</p><blockquote><strong>Binary Search</strong></blockquote><ol><li>If we encounter the peak, we return it.</li><li>If we fall upon slope up condition, we shift left boundary to mid+1.</li><li>If we fall upon slope down condition, we shift right boundary to mid-1.</li></ol><pre>class Solution:<br>    def findPeakElement(self, arr: List[int]) -&gt; int:<br> <br>        n=len(arr)<br>        if n==1:<br>            return 0<br>        if n==2:<br>            if arr[0]&gt;arr[1]:<br>                return 0<br>            return 1<br>        l, r = 0, n-1<br>        <br>       <strong> # Binary Search </strong><br>        <br>        while l&lt;=r:<br>            <br>            mid=(l+r)//2<br>            <br>            <strong># If mid is Peak</strong><br>            if (mid==0 or arr[mid]&gt;arr[mid-1]) and (mid==n-1 or <br>            arr[mid]&gt;arr[mid+1]):<br>                return mid<br>            <br>            <strong># If mid is in slope up</strong><br>            if mid==0 or (mid!=n-1 and arr[mid]&lt;arr[mid+1]):<br>                l=mid+1<br>            <br>          <strong>  # If mid is in slope down</strong><br>            else:<br>                r=mid-1</pre><p>Time = O(log N) and Space = O(1)</p><h3>1095. Find in Mountain Array</h3><p>Difficulty — Hard</p><p>Link — <a href="https://leetcode.com/problems/find-in-mountain-array/">https://leetcode.com/problems/find-in-mountain-array/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*Se4z6qPJ8AvTI0ux5hn8mw.png" /></figure><p>We know that Binary Search can be used ONLY in a sorted array. A bitonic array is not completely sorted, hence it is not possible to use binary search directly. Because of this, we take a slightly different approach.</p><p>A bitonic array can be divided into two monotonic subarrays if we have access to its peak. Then we can use binary search on both subarrays separately. Since we have already discussed the algorithm to find the peak of a bitonic array, we can proceed with this method —</p><ol><li>Find the peak of the bitonic array using binary search.</li><li>If the peak element is the target, return the peak.</li><li>Use binary search on the increasing and decreasing subarray consecutively to find the target.</li><li>If the target is found in neither, return -1.</li></ol><pre>class Solution:<br>    def findInMountainArray(self, target: int, mountain_arr: &#39;MountainArray&#39;) -&gt; int:<br>        <br>        <strong># 1. Find Peak</strong></pre><pre>        n=mountain_arr.length()<br>        l, r = 0, n-1<br>        peak=0     <br>        while l&lt;=r:<br>            <br>            mid=(l+r)//2<br>            val=mountain_arr.get(mid)<br><br>            if mid==0 or (mid!=n-1 and val&lt;mountain_arr.get(mid+1)):<br>                l=mid+1<br>            <br>            elif mid==n-1 or (mid!=0 and val&lt;mountain_arr.get(mid-<br>            1)):<br>                r=mid-1<br>                <br>            else:<br>                peak=mid<br>                break</pre><pre>        <strong># 2. If Peak Element is Target</strong></pre><pre>        if mountain_arr.get(peak)==target:<br>            return mid<br>        <br>        <strong># 3. Search in Increasing Subarray</strong><br>        l, r = 0, peak-1<br>             <br>        while l&lt;=r:<br>            mid=(l+r)//2<br>            val=mountain_arr.get(mid)<br>            if val==target:<br>                return mid<br>            elif val&gt;target:<br>                r=mid-1<br>            else:<br>                l=mid+1<br>                <br>       <strong> # 4. Search in Decreasing Subarray</strong><br>        l, r = peak+1, n-1<br>             <br>        while l&lt;=r:<br>            mid=(l+r)//2<br>            val=mountain_arr.get(mid)<br>            if val==target:<br>                return mid<br>            elif val&lt;target:<br>                r=mid-1<br>            else:<br>                l=mid+1<br>        <br>        return -1</pre><p><strong>Time Complexity —</strong></p><p>Let there be M elements to the left and N elements to the right of the peak.</p><p>= O(log (M+N)) for <em>finding peak</em> + O(log M) for <em>left subarray</em> + O(log N) for <em>right subarray</em></p><p>= O(log (M+N)) or O(log N) if there are N elements in total in the array</p><p>Time = O(log N) and Space = O(1)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69bb218ba7d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search Problems — Easy to Medium Leetcode]]></title>
            <link>https://medium.com/@dayita.chaudhuri/binary-search-problems-be1fa23f9eac?source=rss-a334f21539c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/be1fa23f9eac</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sad]]></category>
            <dc:creator><![CDATA[Dayita Chaudhuri]]></dc:creator>
            <pubDate>Sat, 06 Aug 2022 19:17:17 GMT</pubDate>
            <atom:updated>2022-08-21T12:38:27.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>Binary Search Problems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DENauUixUf2DS-VfgKCXlA.png" /></figure><p><strong><em>Binary Search</em></strong><em> is a </em><a href="https://www.geeksforgeeks.org/searching-algorithms/"><em>searching algorithm</em></a><em> used in a sorted array by </em><strong><em>repeatedly dividing the search interval in half</em></strong><em>. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to </em><strong><em>O(Log n)</em></strong><em>.</em></p><p><strong>Binary Search Algorithm:</strong></p><ul><li>Begin with the mid element of the whole array as a search key.</li><li>If the value of the search key is equal to the item then return an index of the search key.</li><li>Or if the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.</li><li>Otherwise, narrow it to the upper half.</li><li>Repeatedly check from the second point until the value is found or the interval is empty.</li></ul><p>Binary Search Algorithm can be implemented in the following two ways</p><ol><li>Iterative Method</li><li>Recursive Method</li></ol><blockquote><strong><em>Iterative Binary Search</em></strong></blockquote><pre>class Solution:<br>    def search(self, nums: List[int], target: int) -&gt; int:<br>        <br>        start, end = 0, len(nums)-1<br>        <br>        while start&lt;=end:<br>            mid=(start+end)//2<br>            if nums[mid]==target:<br>                <strong>return mid</strong><br>            elif nums[mid]&gt;target:<br>                <strong>end=mid-1</strong><br>            else:<br>                <strong>start=mid+1</strong><br>        <br>        return -1</pre><blockquote><strong><em>Recursive Binary Search</em></strong></blockquote><pre>class Solution:<br>    def search(self, nums: List[int], target: int) -&gt; int:<br>        <br><strong>        def binsearch(nums, target, start, end):</strong>           <br>           if start&lt;end:<br>                mid=(start+end)//2<br>                if nums[mid]==target:<br>                    return mid<br>                elif nums[mid]&gt;target:<br>                    return <strong>binsearch(nums,target,start,mid-1)</strong><br>                else:<br>                    return <strong>binsearch(nums,target,mid+1,end)</strong><br>            return -1<br>        <br>        return binsearch(nums,target,0,len(nums)-1)</pre><p>Check out this video for some important binary search questions asked in interviews frequently —</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FW9QJ8HaRvJQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DW9QJ8HaRvJQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FW9QJ8HaRvJQ%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/6a7fa659532de0bd1af31518c34d2a2c/href">https://medium.com/media/6a7fa659532de0bd1af31518c34d2a2c/href</a></iframe><p>Contents —</p><ul><li>Find Smallest Letter Greater Than Target</li><li>Find First and Last Position of Element in Sorted Array</li><li>Search Insert Position</li><li>Search a 2D Matrix</li><li>Search in Rotated Sorted Array</li><li>Power (x,n)</li></ul><h3>744. Find Smallest Letter Greater Than Target</h3><p>Difficulty — Easy</p><p>Link — <a href="https://leetcode.com/problems/find-smallest-letter-greater-than-target/">https://leetcode.com/problems/find-smallest-letter-greater-than-target/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*849DmeKMWLdKjLgIUre4BA.png" /></figure><blockquote><strong>Linear Search —</strong></blockquote><pre>class Solution:<br>    def nextGreatestLetter(self, letters: List[str], target: str) -&gt; str:</pre><pre>        for l in letters:<br>            if l&gt;target:<br>                return l</pre><pre>        return letters[0]</pre><p>Time = O(N) and Space = O(1)</p><blockquote><strong>Binary Search</strong></blockquote><pre>class Solution:<br>    def nextGreatestLetter(self, letters: List[str], target: str) -&gt; str:</pre><pre>        l,r=0,len(letters)-1<br>        while l&lt;=r:<br>            mid=(l+r)//2<br>            if letters[mid]&gt;target:<br>                if mid==0 or letters[mid-1]&lt;=target:<br>                    return letters[mid]<br>                else:<br>                    r=mid-1<br>            else:<br>                l=mid+1</pre><pre>        return letters[0]</pre><p>Time = O(log N) and Space = O(1)</p><h3>34. Find First and Last Position of Element in Sorted Array</h3><p>Difficulty — Medium</p><p>Link — <a href="https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/">https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*WkhyRI_wDwVW-d8yuwBh8g.png" /></figure><blockquote><strong>Linear Search —</strong></blockquote><pre>class Solution:<br>    def searchRange(self, nums: List[int], target: int) -&gt; List[int]:</pre><pre>        start, end = -1, -1<br>        for i in range(0,len(nums)):<br>            if nums[i]==target:<br>                if start==-1 or i&lt;start:<br>                    start=i<br>                if end==-1 or i&gt;end:<br>                    end=i</pre><pre>        return [start,end]</pre><p>Time = O(N) and Space = O(1)</p><blockquote><strong>Binary Search</strong></blockquote><p>We use two different binary search loops for first position and last position with the value.</p><pre>class Solution:<br>    def searchRange(self, nums: List[int], target: int) -&gt; List[int]:</pre><pre>        start, end = -1, -1<br>        n=len(nums)<br>        <br>        <strong># Binary Search to find First Position</strong><br>        <br>        l,r = 0,n-1<br>        while l&lt;=r:<br>            mid=(l+r)//2<br>            if (nums[mid]==target) and (mid==0 or nums[mid-1]<br>            &lt;target):<br>                start=mid<br>                break<br>            elif nums[mid]&lt;target:<br>                l=mid+1<br>            else:<br>                r=mid-1<br>                <br>       <strong> # Binary Search to find Last Position</strong><br>        <br>        l,r = 0,n-1<br>        while l&lt;=r:<br>            mid=(l+r)//2<br>            if (nums[mid]==target) and (mid==n-1 or <br>            nums[mid+1]&gt;target):<br>                end=mid<br>                break<br>            elif nums[mid]&gt;target:<br>                r=mid-1<br>            else:<br>                l=mid+1 <br>                <br>        return [start,end]</pre><p>Time = O(log N) and Space = O(1)</p><h3>35. Search Insert Position</h3><p>Difficulty — Easy</p><p>Link — <a href="https://leetcode.com/problems/search-insert-position/">https://leetcode.com/problems/search-insert-position/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*ii_Zdew6meWIMy7VpTm1eQ.png" /></figure><blockquote><strong>Binary Search</strong></blockquote><p>Target cannot be found if one of the following conditions holds.</p><ul><li>First element &gt; target</li><li>Last element &lt; target</li><li>There exists an index i such that nums[i]&lt;target&lt;nums[i+1]</li></ul><p>We can use binary search with modified return conditions to include the case where the target cannot be found and return the position of the element just greater than the target in that case.</p><ol><li>If <strong>nums[mid] = target</strong>, return mid.</li><li>If <strong>nums[mid]&gt;target</strong>, there can be two cases for which target does not exist (mid is 0 or nums[mid-1]&lt;target). In that case, return mid. If none of these holds, change the left value to mid+1 and continue the binary search.</li><li>If<strong> nums[mid]&lt;target</strong>, there can be two cases for which target does not exist (mid is n-1 or nums[mid+1]&gt;target). In that case, return mid+1. If none of these holds, change the right value to mid-1 and continue the binary search.</li></ol><pre>class Solution:<br>    def searchInsert(self, nums: List[int], target: int) -&gt; int:</pre><pre>        n=len(nums)<br>        l,r=0,n-1</pre><pre>        while l&lt;=r:<br>            mid=(l+r)//2</pre><pre>            if nums[mid]==target:<br>                <strong>return mid</strong></pre><pre>            elif nums[mid]&gt;target:<br>                if mid==0 or nums[mid-1]&lt;target:<br>                    <strong>return mid</strong><br>                else:<br>                    <strong>r=mid-1</strong><br>            else:<br>                if mid==n-1 or nums[mid+1]&gt;target:<br>                    <strong>return mid+1</strong><br>                else:<br>                    <strong>l=mid+1</strong></pre><p>Time = O(log N) and Space = O(1)</p><h3>74. Search a 2D Matrix</h3><p>Difficulty — Medium</p><p>Link — <a href="https://leetcode.com/problems/search-a-2d-matrix/">https://leetcode.com/problems/search-a-2d-matrix/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*k5WP_cbOEIQwzrD81G8wcw.png" /></figure><blockquote><strong>Linear Search —</strong></blockquote><pre>class Solution:<br>    def searchMatrix(self, matrix: List[List[int]], target: int) -&gt; bool:</pre><pre>       for row in range(len(matrix)):<br>		for col in range(len(matrix[i])):<br>			if matrix[i][j]==target:<br>				return True<br>	return False</pre><p>Time = O(M*N) and Space = O(1)</p><blockquote><strong>Binary Search —</strong></blockquote><pre>class Solution:<br>    def searchMatrix(self, matrix: List[List[int]], target: int) -&gt; bool:<br>        <br>        m=len(matrix)<br>        n=len(matrix[0])<br>        low=0<br>        high=n*m-1<br>        <br>        while low&lt;=high:<br>            <br>            mid=(low+high)//2<br>            <br>            if <strong>matrix[mid//n][mid%n]</strong>==target:<br>                return True<br>            <br>            elif <strong>matrix[mid//n][mid%n]</strong>&gt;target:<br>                high=mid-1<br>                <br>            else:<br>                low=mid+1<br>        <br>        return False</pre><p>Time = O(log M*N) and Space = O(1)</p><h3>33. Search in Rotated Sorted Array</h3><p>Difficulty — Medium</p><p>Link — <a href="https://leetcode.com/problems/search-in-rotated-sorted-array/">https://leetcode.com/problems/search-in-rotated-sorted-array/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*-PgKsPq1LhySo9oG6AwTTg.png" /></figure><blockquote><strong>Linear Search</strong></blockquote><pre>class Solution:<br>    def search(self, nums: List[int], target: int) -&gt; int:</pre><pre>         for i in range(0,len(nums)):<br>            if nums[i]==target:<br>                return i</pre><pre>         return -1</pre><p>Time = O(N) and Space = O(1)</p><blockquote><strong>Binary Search</strong></blockquote><pre>class Solution:<br>    def search(self, nums: List[int], target: int) -&gt; int:<br>        <br>        n=len(nums)<br>        <br>        low,high=0,n-1<br>        <br>        while low&lt;=high:<br>            <br>            mid=(low+high)//2<br>            <br>            <strong># If target is found</strong><br>            if nums[mid]==target:<br>                return mid<br>            <br>           <strong> # If left half is sorted</strong><br>            if nums[low]&lt;=nums[mid]:<br>                if target&gt;nums[mid] or target&lt;nums[low]:<br>                    low=mid+1<br>                else:<br>                    high=mid-1<br>                    <br>   <strong>         # If right half is sorted  </strong>     <br>            else:<br>                if target&lt;nums[mid] or target&gt;nums[high]:<br>                    high=mid-1<br>                else:<br>                    low=mid+1<br>                <br>        return -1</pre><p>Time = O(log N) and Space = O(1)</p><h3>50. Pow(x, n)</h3><p>Difficulty — Medium</p><p>Link — <a href="https://leetcode.com/problems/powx-n/">https://leetcode.com/problems/powx-n/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*CTvMSM8ChvUyMITf_ZD62A.png" /></figure><p>One way to solve this is by simply running loop n times and finding x^n.</p><blockquote><strong>Brute Force</strong></blockquote><pre>class Solution:<br>    def myPow(self, x: float, n: int) -&gt; float:<br>       <strong> <br>        # Base Conditions</strong><br>        if x==0 or x==1:<br>            return x<br>        if n==0:<br>            return 1<br>        <br>      <strong>  # Negative Power</strong><br>        if n&lt;0:<br>            return self.myPow(1/x,-n)<br>        <br>        res=1</pre><pre>    <strong>    # Loop</strong><br>        for i in range(0,n):<br>            res=res*x<br>       <br>        return res</pre><p>Time = O(N) and Space = O(1)</p><p>We can reduce the time by using binary search. We know that if the power is even, we can square the value and reduce the number of iterations by about half.</p><ul><li>If x is 0 or 1, return x. If n is 0, return 1.</li><li>If power is negative, recurse the same function with x=1/x and n=(-n)</li><li>If power is even, return myPow(x*x, n//2)</li><li>If power is odd, return x * myPow(x*x, n//2)</li></ul><blockquote><strong>Binary Search</strong></blockquote><pre>class Solution:<br>    def myPow(self, x: float, n: int) -&gt; float:<br>       <strong> <br>        # Base Conditions</strong><br>        if x==0 or x==1:<br>            return x<br>        if n==0:<br>            return 1<br>        <br>      <strong>  # Case of Negative Power</strong><br>        if n&lt;0:<br>            return self.myPow(1/x,-n)<br>        <br>    <strong>    # If power is even</strong><br>        if n%2==0:<br>            return self.myPow(x*x, n//2)<br>        <br>     <strong>   # If power is odd</strong><br>        else:<br>            return x*self.myPow(x*x,n//2)</pre><p>Time = O(log N) and Space = O(1)</p><p>Now we will move to a very different type of question. These are very important questions and if you can get a good grasp of the method of solving one, you can solve the rest easily. The main difficulty is in understanding how and where to implement binary search.</p><h3>1011. Capacity To Ship Packages Within D Days</h3><p>Difficulty — Medium</p><p>Link — <a href="https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/">https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ST2he6nc2bJv8bA6LndpOg.png" /></figure><p>The aim is to calculate the min capacity required to ship all packages in given number of days. What if we try to turn the question around and calculate the number of days required to ship all packages with given capacity? That way we can search for all capacities between “<em>maximum weight”</em> (no. of days will be minimum) and “<em>sum of all weights” </em>(no. of days will be maximum) and locate the value which is just less than or equal to our given value of days.</p><p>We will use binary search to do the searching.</p><ul><li>Define a function to calculate the number of days for a given capacity. Use greedy algorithm and single traversal for it.</li><li>Define the left extreme as the maximum weight in weights, and the right extreme as the sum of all weights.</li><li>Use binary search. While left≤right, mid=(left+right)//2.</li><li>If the number of days for “mid” capacity exceeds the given limit, increase the capacity by increasing the left extreme to mid+1.</li><li>Else decrease the capacity by decreasing the right extreme to mid — 1.</li><li>The final value of left at which we exit the loop will be our required answer.</li></ul><p>Take a few minutes to carefully analyse the Python Code given below.</p><pre>class Solution:<br>    def shipWithinDays(self, weights: List[int], days: int) -&gt; int:<br>        <br><strong>        # Function to Calculate Number of Days</strong><br>        def calculateDays(capacity):<br>            d, curr = 0, 0<br>            for w in weights:<br>                if curr + w &gt; capacity:<br>                    d += 1<br>                    curr = 0<br>                curr += w<br>            if curr &gt; 0:<br>                d+=1<br>            return d<br><strong>        <br>        # Find left and right extremes</strong><br>        <br>        left, right = 0, 0<br>        for w in weights:<br>            if w &gt; left:<br>                left = w<br>            right += w<br>            <br>        <strong># Binary Search</strong><br>        <br>        while left &lt;= right:<br>            <br>            mid = (left + right) // 2<br>            <br>            <strong># If days is exceeding given limit, increase the chosen <br>            capacity.</strong><br>            if calculateDays(mid)&gt;days:<br>                left = mid + 1<br>            <br>            <strong># If days is less than given limit, decrease the chosen <br>            capacity.</strong><br>            else:<br>                right = mid - 1<br>        <strong><br>        # Final value of left at which we exit the loop is the    <br>        solution.</strong><br>        return left</pre><p>Time = O(N log N) and Space = O(1)</p><h3>1760. Minimum Limit of Balls in a Bag</h3><p>Difficulty — Medium</p><p>Link — <a href="https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/">https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*VUdCEPRYHOezMDeCixK1jA.png" /></figure><p>This question might not seem like the last one, but it is very very similar. The solution is exactly the same. We just need to find the similarity.</p><p>For the given maximum number of operations, we need to find the minimum penalty. What if we turn the question around the last time and find the minimum number of operations required to have a given penalty? It can be calculated easily using only a single traversal. We can search for the number of operations just less than or equal to the given number of operations, for penalties in the range of 1 to “<em>maximum number of balls in any bag”</em>.</p><p>We will use binary search to do the searching.</p><ul><li>Define a function to calculate the minimum number of operations required to have a given penalty. Use a single traversal for it.</li><li>Define the left extreme as 1, and the right extreme as the <em>maximum number of balls in any bag</em>.</li><li>Use binary search. While left≤right, mid=(left+right)//2.</li><li>If the number of operations for the “mid” penalty exceeds the given limit, increase the penalty by increasing the left extreme to mid+1.</li><li>Else decrease the penalty by decreasing the right extreme to mid — 1.</li><li>The final value of left at which we exit the loop will be our required answer.</li></ul><pre>class Solution:<br>    def minimumSize(self, nums: List[int], maxOperations: int) -&gt; int:<br>        <br><strong>        # Function to Calculate Number of Operations</strong><br>        <br>        def bags(capacity, nums):<br>            count = 0<br>            for val in nums:<br>                if val &lt;= capacity:<br>                    continue<br>                if val % capacity == 0:<br>                    count += val // capacity - 1<br>                else:<br>                    count += val // capacity<br>            return count<br><strong>        <br>        # Find left and right extremes</strong><br>        <br>        left = 1<br>        right = 1<br>        for n in nums:<br>            if n &gt; right:<br>                right = n<br>                <br>    <strong>    # Binary Search</strong><br>        <br>        while left &lt;= right:<br>            mid = (left + right) // 2<br>            <br>            <strong># If operations is exceeding given limit, increase the <br>            penalty.</strong><br>            if bags(mid,nums) &gt; maxOperations:<br>                left = mid+1<br>                <br>            <strong># If operations is less than given limit, decrease the <br>            penalty.</strong><br>            else:<br>                right = mid-1<br>                <br>        return left</pre><p>Time = O(N log N) and Space = O(1)</p><p>Go through the above problems and please use the comments section to drop your questions and suggestions. Best of luck and goodbye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be1fa23f9eac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trapping Water Problems — Arrays, Stack]]></title>
            <link>https://medium.com/@dayita.chaudhuri/trapping-water-problems-arrays-stack-b75ad03c6712?source=rss-a334f21539c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b75ad03c6712</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dayita Chaudhuri]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 09:33:05 GMT</pubDate>
            <atom:updated>2022-07-16T20:21:21.780Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trapping Water Problems — Arrays, Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DENauUixUf2DS-VfgKCXlA.png" /></figure><p>Contents —</p><ol><li>Trapping Rainwater</li><li>Trapping Rainwater 2</li><li>Container With Most Water</li></ol><h3>42. Trapping Rain Water</h3><p>Leetcode — <a href="https://leetcode.com/problems/trapping-rain-water/">https://leetcode.com/problems/trapping-rain-water/</a></p><p>Difficulty — Hard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*yD5Ov7n0nM1Ps3r8HBBAdA.png" /></figure><p>This question is similar to Largest Rectangle in Histogram/Maximum Area in Histogram question in terms of approach.</p><p>We can see that <strong>total water = Σ Water stored at each index.</strong></p><p>We need to think about when water is stored in a particular index and how much is stored. Water is stored at index i when there is a building to its left with height &gt; height[i] and also a building to its right with a height &gt; height[i].</p><p>On drawing the diagram we see that the left and right boundaries are NOT given by Nearest Greater Element, rather it IS given by Greatest Element to left and Greatest Element to Right.</p><blockquote><strong>Brute Force Approach —</strong></blockquote><p>For each index, find Greatest Element to Left, Greatest Element to Right and calculate the Water Stored at the index.</p><pre>class Solution:<br>    def trap(self, height: List[int]) -&gt; int:<br>        <br>        n=len(height)<br>        water=0<br>        <br>        for i in range(1,n-1):<br>            left,right=0,0<br>            <br>            <strong># Left Limit</strong><br>            for j in range(0,i+1):<br>                left=max(left,height[j])<br>                <br>           <strong> # Right Limit</strong><br>            for j in range(i,n):<br>                right=max(right,height[j])<br>            <br>            <strong># Water</strong><br>            water+=min(left,right)-height[i]<br>            <br>        return water</pre><p>Time = O(N²) and Space = O(1)</p><blockquote><strong>Optimised Approach Using Extra Space —</strong></blockquote><p>In the previous approach, we are needing O(N) Time to calculate Left and Right Limits. Since we are doing it individually for each index, we are getting O(N²) time. If we can pre-calculate the limits and store them in an array to be accessed later, we can reduce the time complexity to O(N) at the cost of extra space.</p><p><strong>Find Greatest Element to Left for each index :</strong></p><ol><li>Use a left array. Initialise it with all values 0 and left[0]=height[0] since there is no element to the left of height[0].</li><li>For each element, left limit = max (curr element, left limit of the element to its left). We traverse left to right and update all left[i].</li></ol><p><strong>Find Greatest Element to Right for each index :</strong></p><ol><li>Use a right array. Initialise it with all values 0 and right[n-1]=height[n-1] since there is no element to the right of height[n-1].</li><li>For each element, right limit = max (curr element, right limit of the element to its right). We traverse from right to left and update all right[i].</li></ol><p><strong>Find water stored at each index :</strong></p><ol><li>For each index i, water stored = min(left[i], right[i]) — height[i]</li><li>Total water = Σ Water stored at each index</li></ol><pre>class Solution:<br>    def trap(self, heights: List[int]) -&gt; int:<br>        <br>        n=len(heights)<br>        <br>        <strong># Define Left and Right Limit Arrays</strong></pre><pre>        left=[0]*n<br>        right=[0]*n<br>        left[0]=heights[0]<br>        right[n-1]=heights[n-1]<br>        <br>        <strong># Find Left and Right Limits</strong></pre><pre>        for i in range(1,n):<br>            left[i]=max(left[i-1],heights[i])<br>            right[n-1-i]=max(right[n-i],heights[n-1-i])<br>             <br>        <strong># Find Volume of water at each index</strong></pre><pre>        water=0<br>        for i in range(0,n):<br>            water+=min(left[i],right[i])-heights[i]<br>        return water</pre><p>Time = O(N) + O(N) = O(N)</p><p>Space = O(N) + O(N) = O(N)</p><blockquote><strong>Two Pointer Approach —</strong></blockquote><p>Can we solve the above problem in constant space?</p><p>We only need the minimum of Left Greatest Element and Right Greatest Element to find water at any index. We don&#39;t need both. If we have any one of the two and we can prove that there exists at least one value greater than the one we have on the opposite side, we can find the volume of water.</p><p>Hence we can solve this problem by using two pointers, each initialising from the left and right ends and keeping a record of the current Left and Right Greatest Elements.</p><ol><li>Initialise left and right as 0, n-1, and leftMax and rightMax as height[0] and height[n-1].</li><li>Keep comparing height[left] and height[right] as long as left and right do not coincide.</li><li>If height[left] ≤ height[right], min(Left Greatest Element, Right Greatest Element) is LGE. If height[left]&gt;leftMax, update leftMax. Else add to water, leftMax — height[left]. Increment left.</li><li>If height[left] &gt; height[right], min(Left Greatest Element, Right Greatest Element) is RGE. If height[right]&gt;rightMax, update rightMax. Else add to water, rightMax — height[right]. Decrement right.</li></ol><pre>class Solution:<br>    def trap(self, height: List[int]) -&gt; int:<br>        <br>        left,right=0,len(height)-1<br>        leftMax,rightMax=height[0],height[len(height)-1]<br>        water=0<br>        <br>        <strong># If left and right become equal, exit the loop</strong></pre><pre>while left&lt;right:<br>            <br>            <strong># If height[left] is less, for left min(LGE and RGE) is <br>            leftMax.</strong></pre><pre>            if height[left]&lt;height[right]:<br>                if height[left]&gt;leftMax:<br>                    leftMax=height[left]<br>                else:<br>                    water+=leftMax-height[left]<br>                left+=1<br>            <br>            <strong># If height[right] is less, for left min(LGE and RGE) is <br>            rightMax.</strong></pre><pre>            else:<br>                if height[right]&gt;rightMax:<br>                    rightMax=height[right]<br>                else:<br>                    water+=rightMax-height[right]<br>                right-=1<br>        <br>        return water</pre><p>Time = O(N) and Space = O(1)</p><h3>407. Trapping Rain Water II</h3><p>Leetcode — <a href="https://leetcode.com/problems/trapping-rain-water-ii/">https://leetcode.com/problems/trapping-rain-water-ii/</a></p><p>Difficulty — Hard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*WjsFPMXn428ivChHgPkdJw.png" /></figure><p>UNSOLVED</p><h3>11. Container With Most Water</h3><p>Leetcode — <a href="https://leetcode.com/problems/container-with-most-water/">https://leetcode.com/problems/container-with-most-water/</a></p><p>Difficulty —Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1RGHddK3-RchVPJ-EROfw.png" /></figure><p>This question has a very different approach compared to Trapping Rainwater. In Trapping Rainwater Problem, the total water was the sum of water at all possible places. But here this is not the case. The differences to note are :</p><ul><li>As is evident from the diagram, the maximum water may or may not contain all heights inside it.</li><li>Moreover, unlike previous questions, water is stored between heights and not on top of them only.</li></ul><blockquote><strong>Brute Force —</strong></blockquote><p>Brute force solution will be to check water and compare with maxWater for every pair of heights in the array.</p><pre>class Solution:<br>    def maxArea(self, height: List[int]) -&gt; int:<br>        <br>        n=len(height)<br>        maxWater=0<br>        <br>        for i in range(0,n-1):<br>            for j in range(i+1,n):<br>                water=min(height[i],height[j])*(j-i)<br>                if water&gt;maxWater:<br>                    maxWater=water<br>                    <br>        return maxWater</pre><p>Time = O(N²) and Space = O(1)</p><blockquote><strong>Two Pointer Approach —</strong></blockquote><p>We can see that it is an optimisation problem. Hence our first instinct will be Greedy approach. We start left and right from the left and right ends and calculate the amount of water. Following that, we keep the larger end intact and move the smaller end closer inside, and we continue doing so until left and right coincide.</p><ol><li>Initialise left at 0, right at n-1, maxWater as 0.</li><li>Iterate as long as left and right do not coincide. If Left Value &lt; Right Value, height = Left Value. Increment Left Value. If left Value &gt; Right Value, height = Right Value. Decrement Right Value.</li><li>The volume of water = height * width. Update maxWater if required.</li></ol><pre>class Solution:<br>    def maxArea(self, height: List[int]) -&gt; int:<br>        <br>        n=len(height)<br>        left,right=0,n-1<br>        maxWater=0<br>        <br>        while left&lt;right:<br>            <br>            <strong># If left is less, increment left.</strong><br>            if height[left]&lt;height[right]:<br>                water=height[left]*(right-left)<br>                left+=1<br>                <br>           <strong> # If right is less, decreement right.</strong><br>            else:<br>                water=height[right]*(right-left)<br>                right-=1<br>                <br>            <strong># Update water.</strong><br>            if water&gt;maxWater:<br>                maxWater=water<br>        <br>        return maxWater</pre><p>Time = O(N) and Space = O(1)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b75ad03c6712" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NGE and Similar Questions — Stacks]]></title>
            <link>https://medium.com/@dayita.chaudhuri/nge-and-similar-questions-stacks-ac19776b37a5?source=rss-a334f21539c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac19776b37a5</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[sad]]></category>
            <dc:creator><![CDATA[Dayita Chaudhuri]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 05:49:46 GMT</pubDate>
            <atom:updated>2022-07-08T15:32:03.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>NGE and Similar Questions — Stacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DENauUixUf2DS-VfgKCXlA.png" /></figure><p>Contents —</p><ol><li>Next Greater Element I</li><li>Next Greater Element II</li><li>Largest Rectangle in Histogram</li><li>Maximum Rectangle in Binary Matrix</li><li>Stock Span</li><li>Daily Temperatures</li></ol><p>This section contains 5 very similar stack questions of one particular pattern that is very important from an interview point of view.</p><p><strong>Youtube Resources —</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrHQI4mrJ3cg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrHQI4mrJ3cg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrHQI4mrJ3cg%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/da9bb920ae6975298e63b74bb19c7185/href">https://medium.com/media/da9bb920ae6975298e63b74bb19c7185/href</a></iframe><h3>496. Next Greater Element I</h3><p>Leetcode — <a href="https://leetcode.com/problems/next-greater-element-i/">https://leetcode.com/problems/next-greater-element-i/</a></p><p>Difficulty — Easy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*osKv8sVxVOaC0HQnSAWMFA.png" /></figure><p><strong>Brute Force —</strong></p><p>For each element, traverse the right elements and find the first value greater than the current element.</p><pre>class Solution:<br>    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -&gt; List[int]:</pre><pre>        ans={}<br>        res=[]</pre><pre>        for i in range(0,len(nums2):<br>            ans[nums2[i]]=-1<br>            for j in range(i+1,len(nums2)):<br>                if nums2[j]&gt;nums2[i]:<br>                    ans[nums2[i]]=nums2[j]<br>                    break</pre><pre>        for val in nums1:<br>            res.append(ans[val])</pre><pre>return res</pre><p>Time = O(N²) and Space = O(1)</p><p><strong>Optimal Solution Using Stack —</strong></p><ol><li>Start traversing from the last element. Initialise a stack and push the last element. In the solution, set NGE(last element) = -1.</li><li>Iterate i from n-1 to 0. In each iteration, pop values from the stack as long as the stack has values and stack[-1]≤array[i].</li><li>If stack becomes empty, set NGE(array[i]) = -1.</li><li>Else, set NGE(array[i]) =stack[-1].</li><li>In the end push array[i] to the stack.</li></ol><pre>class Solution:<br>    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -&gt; List[int]:<br>        <br>        stack=[nums2[-1]]<br>        ans={nums2[-1]:-1}<br>        <br>        for i in range(len(nums2)-2,-1,-1):<br>            <br>            <strong># While top of stack &lt;= element, pop stack.</strong><br>            while stack and stack[-1]&lt;=nums2[i]:<br>                stack.pop()<br>             <br>            <strong># If stack becomes empty, NGE = (-1)</strong><br>            if len(stack)==0:<br>                ans[nums2[i]]=-1<br>            <br>            <strong># Else NGE = top of stack.</strong><br>            else:<br>                ans[nums2[i]]=stack[-1]<br>                <br>            stack.append(nums2[i])<br>            <br>        res=[]<br>        for val in nums1:<br>            res.append(ans[val])<br>            <br>        return res</pre><p>Time = O(N) and Space = O(N)</p><h3>503. Next Greater Element II</h3><p>Leetcode — <a href="https://leetcode.com/problems/next-greater-element-ii/">https://leetcode.com/problems/next-greater-element-ii/</a></p><p>Difficulty — Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*TIyfPhcSxHJVHDZ2QKByfA.png" /></figure><p>Note — <em>Here the array is circular. Ie after the last element comes the first element. Hence only the largest element will have NGE = -1.</em></p><p><strong>Brute Force —</strong></p><p>For each element, traverse to the right using i=(i+1)%n until we reach the same element. If we get a value &gt; value of the current element, that is our NGE. Else if we reach the same element again, NGE = -1.</p><pre>class Solution:<br>    def nextGreaterElements(self, nums: List[int]) -&gt; List[int]:</pre><pre>    ans=[0]*len(nums)<br>        for i in range(0,len(nums)):<br>            ans[i]=-1<br>            j=(i+1)%len(nums)<br>            while j!=i:<br>                if nums[j]&gt;nums[i]:<br>                    ans[i]=nums[j]<br>                    break<br>                j=(j+1)%len(nums)</pre><pre>     return ans</pre><p><strong>Optimal Solution Using Stack —</strong></p><p>Very similar to the last solution. The only difference is that in this one, we initialise the stack by pushing all elements of the array (except the last one) in reverse order. This adds to the circular property of the array.</p><ol><li>Initialise stack by pushing all nums[i] for i in range(n-2,-1,-1) → All elements except the last one. Initialise ans array with n items, each of 0 value.</li><li>Start traversing from the last element. Now the algorithm will be the same as the last problem.</li><li>Iterate i from n-1 to 0. In each iteration, pop values from the stack as long as the stack has values and stack[-1]≤array[i].</li><li>If stack becomes empty, set NGE(array[i]) = -1.</li><li>Else, set NGE(array[i]) =stack[-1].</li><li>In the end push array[i] to the stack.</li></ol><pre>class Solution:<br>    def nextGreaterElements(self, nums: List[int]) -&gt; List[int]:<br>        <br>        ans=[0]*len(nums)<br>        stack=[]<br>        <br>        <strong># Push values from list to stack in reverse order</strong><br>        for j in range(len(nums)-2,-1,-1):<br>            stack.append(nums[j])<br>            <br>        <strong># Iterate list from last element. Follow algorithm similar <br>        to the last.</strong><br>        for i in range(len(nums)-1,-1,-1):<br>            <br>            while stack and stack[-1]&lt;=nums[i]:<br>                stack.pop()<br>                <br>            if len(stack)==0:<br>                ans[i]=-1<br>                <br>            else:<br>                ans[i]=stack[-1]<br>                <br>            stack.append(nums[i])<br>            <br>        return ans</pre><p>Time = O(N) and Space = O(N)</p><h3>739. Daily Temperatures</h3><p>Leetcode — <a href="https://leetcode.com/problems/daily-temperatures/">https://leetcode.com/problems/daily-temperatures/</a></p><p>Difficulty — Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*lfj8YQKHLGf6v07Pxp8mrA.png" /></figure><p>This is a question whose base lies at the Next Greater Element (NGE). The next day where we get a temperature greater than the current temperature will be NGE of the current value. No. of days of wait can be calculated by using (NGE Index — Current Index).</p><p>Hence the only twist here is that instead of storing values as we did in NGE, we need to store the index of the place where the greater value is present so that we can use it to calculate the number of days.</p><ol><li>Initialise the answer array with n 0 values, and a stack.</li><li>Iterate values from right to left.</li><li>While the top of the stack points to value ≤ temperature[i], pop the stack.</li><li>After coming out of the loop, if the stack is not empty, answer[i] is (stack[-1] — i). Otherwise answer[i] is 0.</li></ol><pre>class Solution:<br>    def dailyTemperatures(self, temp: List[int]) -&gt; List[int]:<br>    <br>        n=len(temp)<br>        answer=[0]*n<br>        stack=[]<br>        <br>        <strong># Find index of NGE for each element.Find no. of days by <br>        calculating distance between current index and index of NGE.</strong></pre><pre>        for i in range(n-1,-1,-1):<br>            <br>            while stack and temp[stack[-1]]&lt;=temp[i]:<br>                stack.pop()<br>            if stack:<br>                answer[i]=stack[-1]-i<br>                <br>            stack.append(i)<br>            <br>        return answer</pre><p>Time = O(N) and Space = O(N)</p><h3>84. Largest Rectangle in Histogram</h3><p>Leetcode — <a href="https://leetcode.com/problems/largest-rectangle-in-histogram/">https://leetcode.com/problems/largest-rectangle-in-histogram/</a></p><p>Difficulty — Hard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*29G4doDcehsPyhv1DVaUmQ.png" /></figure><p><strong>Pre-requisites —</strong></p><ul><li>Next Smaller Element (NSE)</li><li>Previous Smaller Element (PSE)</li></ul><p>Both of these can be solved by reusing the Next Greater Element Code with a few minor changes. For smaller element, change condition of while loop to <strong>stack[-1]≥array[i]</strong>. For Previous case, iterate from left to right by changing the for loop to <strong>for i in range(0,n)</strong>.</p><p>From the diagram we observe that —</p><p>Rectangle with array[i] as the height, has left boundary as PSE(i) and right boundary as NSE(i).</p><pre>Height = heights[i]</pre><pre>Width = NSE(i) — PSE(i) — 1</pre><p>Hence we need to find PSE and NSE for each index element. We have already solved this in O(N) time. Then, in one single pass we can find the area for each array[i] as height and keep note of the largest area.</p><ol><li>Create an array right such that right[i] gives the Next Lower Element Index of heights[i].</li><li>Create an array left such that left[i] gives the Previous Lower Element Index of heights[i].</li><li>Use a for loop to traverse through all values of heights[i] and calculate area of rectangle with height = heights[i] and width = right[i]-left[i]-1. Keep record of maximum area obtained.</li></ol><pre>class Solution:<br>    def largestRectangleArea(self, heights: List[int]) -&gt; int:<br>        <br>        n=len(heights)<br>        <br>       <strong> # Next Lower Element Index for each i.</strong></pre><pre>        right=[0]*n<br>        stack=[]</pre><pre>        for i in range(n-1,-1,-1):<br>            while stack and heights[stack[-1]]&gt;=heights[i]:<br>                stack.pop()<br>            if len(stack)==0:<br>                right[i]=n<br>            else:<br>                right[i]=stack[-1]<br>            stack.append(i)<br>        <br>        <strong># Next Lower Element Index for each i.</strong></pre><pre>        left=[0]*n<br>        stack=[]</pre><pre>        for i in range(0,n):<br>            while stack and heights[stack[-1]]&gt;=heights[i]:<br>                stack.pop()<br>            if len(stack)==0:<br>                left[i]=-1<br>            else:<br>                left[i]=stack[-1]<br>            stack.append(i)<br>            <br>        <strong># Area for each heights[i].</strong></pre><pre>        area=0</pre><pre>        for i in range(0,n):<br>            currArea=heights[i]*(right[i]-left[i]-1)<br>            if currArea&gt;area:<br>                area=currArea<br>                <br>        return area</pre><p>Time = O(N) for NLE + O(N) for PLE + O(N) for Area Calculation = O(N)</p><p>Space = O(N) for Stack</p><p>Hence, Time = O(N) and Space = O(N)</p><p><strong>Youtube —</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJ2X70jj_I1o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJ2X70jj_I1o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJ2X70jj_I1o%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/0791bf41f89f1cbcd3538a15a40c3db8/href">https://medium.com/media/0791bf41f89f1cbcd3538a15a40c3db8/href</a></iframe><h3>85. Maximal Rectangle</h3><p>Leetcode — <a href="https://leetcode.com/problems/maximal-rectangle/">https://leetcode.com/problems/maximal-rectangle/</a></p><p>Difficulty — Hard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*NLSq8Ly3FASPmmkZ2Te0wA.png" /></figure><p>Prerequisites —</p><ul><li>Largest Rectangle in Histogram / Maximum Area in Histogram (MAH)</li></ul><pre>class Solution:<br>    <br>    <strong># Maximum Area in Histogram</strong><br>    <br>    def MAH(self,heights: List[int]) -&gt; int:<br>        <br>        n=len(heights)<br>        <br>        <strong># Next Lower Element Index for each i.</strong><br>        right=[0]*n<br>        stack=[]<br>        for i in range(n-1,-1,-1):<br>            while stack and heights[stack[-1]]&gt;=heights[i]:<br>                stack.pop()<br>            if len(stack)==0:<br>                right[i]=n<br>            else:<br>                right[i]=stack[-1]<br>            stack.append(i)<br>        <br>        <strong># Next Lower Element Index for each i.</strong><br>        left=[0]*n<br>        stack=[]<br>        for i in range(0,n):<br>            while stack and heights[stack[-1]]&gt;=heights[i]:<br>                stack.pop()<br>            if len(stack)==0:<br>                left[i]=-1<br>            else:<br>                left[i]=stack[-1]<br>            stack.append(i)<br>            <br>        <strong># Area for each heights[i].</strong><br>        area=0<br>        for i in range(0,n):<br>            currArea=heights[i]*(right[i]-left[i]-1)<br>            if currArea&gt;area:<br>                area=currArea<br>        return area</pre><pre><strong>   # Solution Function</strong></pre><pre>   def maximalRectangle(self, matrix: List[List[str]]) -&gt; int:<br>        <br>        heights=[0]*len(matrix[0])<br>        maxArea=0<br>        <br>        <strong># For each row in matrix, find MAH.</strong><br>        for i in range(0,len(matrix)):<br>            for j in range(0,len(matrix[0])):<br>                if matrix[i][j]==&quot;0&quot;:<br>                    heights[j]=0<br>                else:<br>                    heights[j]+=1<br>            area=self.MAH(heights)</pre><pre><strong>            # Keep Record of largest MAH.</strong><br>            if area&gt;maxArea:<br>                maxArea=area<br>                <br>        return maxArea</pre><p>Time = O(N*M)</p><p>Space = O(M) + O(N) = O(max(M,N))</p><p><strong>Youtube —</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSt0Jf_VmG_g%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSt0Jf_VmG_g&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSt0Jf_VmG_g%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/811269c97e2b2d5ef9faedc18a6e9dba/href">https://medium.com/media/811269c97e2b2d5ef9faedc18a6e9dba/href</a></iframe><h3>901. Online Stock Span</h3><p>Leetcode — <a href="https://leetcode.com/problems/online-stock-span/">https://leetcode.com/problems/online-stock-span/</a></p><p>Difficulty — Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*4TugcqPClwr9d3_vA_-NnA.png" /></figure><p>This is a direct implementation of the Nearest Greater Element to the Left. The code is self-explanatory —</p><pre>class StockSpanner:</pre><pre><strong>    def __init__(self):</strong></pre><pre>        self.stack=[]<br>        self.index=-1<br>        <br>    <strong>def next(self, price: int) -&gt; int:</strong></pre><pre>        self.index += 1<br>        while self.stack and self.stack[-1][0]&lt;=price:<br>            self.stack.pop()</pre><pre>        ans = 0<br>        if self.stack:<br>            ans = self.index-self.stack[-1][1]<br>        else:<br>            ans = self.index+1</pre><pre>        self.stack.append((price, self.index))</pre><pre>        return ans</pre><p>Time Complexity for next() = O(N)</p><p><strong>Youtube —</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fp9T-fE1g1pU%3Flist%3DPL_z_8CaSLPWdeOezg68SKkeLN4-T_jNHd&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dp9T-fE1g1pU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fp9T-fE1g1pU%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/91930a752f9c68820857609f5feb6362/href">https://medium.com/media/91930a752f9c68820857609f5feb6362/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac19776b37a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tower of Hanoi and N Queens — Recursion and Backtracking]]></title>
            <link>https://medium.com/@dayita.chaudhuri/tower-of-hanoi-and-n-queens-recursion-and-backtracking-91b65db9eb4a?source=rss-a334f21539c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/91b65db9eb4a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[n-queens]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[tower-of-hanoi]]></category>
            <dc:creator><![CDATA[Dayita Chaudhuri]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 15:57:33 GMT</pubDate>
            <atom:updated>2022-07-06T20:16:04.893Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tower of Hanoi and N Queens — Recursion and Backtracking</h3><h3>The Tower of Hanoi</h3><p>G4G — <a href="https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/">https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/</a></p><p>The Tower of Hanoi is a mathematical puzzle. We have three rods and n number of disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:</p><ul><li>Only one disk can be moved at a time.</li><li>Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.</li><li>No disk may be placed on top of a smaller disk.</li></ul><p>We can study the solution when number of rods is 2 and 3.</p><h3>Moving 2 disks from A to C via B</h3><p><strong>When n = 2, source = A, destination = C, auxilliary = B,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*vshIAPFWvHew-0Q9" /></figure><ol><li>Disk 2 from A to B.</li><li>Disk 1 from A to C → Disk 1 Placed.</li><li>Disk 2 from B to C → Disk 2 Placed.</li></ol><h3>Moving 3 disks from A to C via B</h3><p><strong>When n = 3, source = A, destination = C, auxilliary = B,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*UYNONXFPuJ5elUL1.gif" /></figure><ol><li>Disk 3 from A to C.</li><li>Disk 2 from A to B.</li><li>Disk 3 from C to B → Disk 2 and 3 Placed at B.</li><li>Disk 1 from A to C → Disk 1 Placed at C.</li><li>Disk 3 from B to A.</li><li>Disk 2 from B to C</li><li>Disk 1 from A to C → Disk 2 and 3 Placed at C.</li></ol><p>Steps 1,2,3 are the same as moving 2 disks from A to B via C. And steps 5,6,7 are the same as moving 2 disks from B to C via A.</p><p><strong>Hence we can divide the problem into subproblems such that —</strong></p><pre>TowerOfHanoi( n, source to destination via auxiliary)</pre><pre>= TowerOfHanoi( n-1, source to auxilliary via destination) <br>+ Move nth disk to destination <br>+ TowerOfHanoi( n-1, auxilliary to destination via source)</pre><p><strong>This can be solved using recursion.</strong></p><ol><li>Move n-1 disks from source to auxiliary.</li><li>Move the nth disk to destination.</li><li>Then move the n-1 disks from auxiliary to destination.</li></ol><pre><strong>def</strong> TowerOfHanoi(n , source, destination, auxilliary):</pre><pre><strong>    if</strong> n <strong>==</strong> 0:</pre><pre><strong>        return</strong></pre><pre>    TowerOfHanoi(n<strong>-</strong>1, source, auxilliary, destination)</pre><pre><strong>    print</strong>(&quot;Move disk&quot;,n,&quot;from rod&quot;,source,&quot;to rod&quot;,destination)</pre><pre>    TowerOfHanoi(n<strong>-</strong>1, auxilliary, destination, source)</pre><pre>n <strong>=</strong> 4</pre><pre>TowerOfHanoi(n, &#39;A&#39;, &#39;C&#39;, &#39;B&#39;)</pre><p>Time = O(2^n) and Space = O(n)</p><p>No. of moves needed for n disks = 2^n — 1.</p><h3>N — Queens</h3><p>Leetcode — <a href="https://leetcode.com/problems/n-queens/">https://leetcode.com/problems/n-queens/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*nr7R-K_Kz9H5SzfKjKN0iw.png" /></figure><p>Let us make some observations —</p><ul><li>One row can have only one queen. Similarly, one column can have only one queen.</li><li>Queens cannot be on the same diagonal. To check this, we need to ensure no queens have the same value of (row+col) or (row-col).</li></ul><p>This problem can hence be divided into subproblems. We place a queen at a certain place and then find possible arrangements of n-1 queens not coinciding with the row, column or diagonal of the current queen.</p><pre>class Solution:<br>    def solveNQueens(self, n: int) -&gt; List[List[str]]:<br>        <br>        ans=[]<br>        columns=[]<br>        posDiag,negDiag=[],[]<br>        board=[[&quot;.&quot;]*n for i in range(0,n)]</pre><pre>        <strong># We find place to put queen in current row.  </strong>    </pre><pre>        def helper(row):</pre><pre><strong>            # If we have reached the end of the row, append the     <br>            board in the specified format to the answer array.</strong></pre><pre>            if row==n:<br>                sol=[&quot;&quot;.join(r) for r in board]<br>                ans.append(sol)<br>            <br>            <strong># Otherwise, we place a queen at each column in the row.</strong></pre><pre>            for col in range(0,n):<br>                if col not in columns and (row+col) not in posDiag and (row-col) not in negDiag:<br>                    <br>                    <strong># if board[row][col] is not attacked by any   <br>                    previously placed queen, we place the queen <br>                    there and update columns, posDiagobal and <br>                    negDiagonal.</strong></pre><pre>                    board[row][col]=&quot;Q&quot;<br>                    columns.append(col)<br>                    posDiag.append(row+col)<br>                    negDiag.append(row-col)<br>                <br>                    <strong># We move to next row</strong></pre><pre>                    helper(row+1)</pre><pre>                   <strong># On coming back we undo the changes we made last <br>                   and try for the next column of the row.</strong><br>                <br>                    board[row][col]=&quot;.&quot;<br>                    columns.pop()<br>                    posDiag.pop()<br>                    negDiag.pop()<br>                <br>        helper(0)<br>        return ans</pre><p>Time = O(N²) since we have to check the conditions for each row and each column.</p><p>Space = O(N²) for the NxN board.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91b65db9eb4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[n-Sum Problems — Arrays Important]]></title>
            <link>https://medium.com/@dayita.chaudhuri/n-sum-problems-on-leetcode-67135a13d825?source=rss-a334f21539c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/67135a13d825</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Dayita Chaudhuri]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 09:36:44 GMT</pubDate>
            <atom:updated>2022-07-08T09:30:43.074Z</atom:updated>
            <content:encoded><![CDATA[<h3>n-Sum Problems — Arrays Important</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DENauUixUf2DS-VfgKCXlA.png" /></figure><p>Contents —</p><ul><li>2 Sum</li><li>2 Sum II</li><li>Count Number of Pairs With Absolute Difference K</li><li>Find All K-Distant Indices in an Array</li><li>3 Sum</li><li>4 Sum</li></ul><p>While solving Day 4 of Striver’s Sheet, I encountered the 2 Sum and 4 Sum problems. I proceeded to Solve all the n-Sum problems in Leetcode to get a better understanding of the problem set and be prepared for all tweaks in an interview.</p><h3>1. Two Sum</h3><p>Question — <a href="https://leetcode.com/problems/two-sum/">https://leetcode.com/problems/two-sum/</a></p><p>Difficulty — Easy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*B6mBxWTLizQKnTKWizrsGQ.png" /></figure><p><strong>Brute Force —</strong></p><p>Use two nested loops to compare every two distinct elements and check if their sum is equal to the target.</p><pre>class Solution:<br>    def twoSum(self, nums: List[int], target: int) -&gt; List[int]:<br>        for i in range(0,len(nums)-1):<br>            for j in range(i+1,len(nums)):<br>                if nums[i]+nums[j]==target:<br>                    return list([i,j])</pre><p>Time = O(N²) and Space = O(1)</p><p><strong>Hashing Solution —</strong></p><p>We can use a hashtable to store the value of target-nums[i] for every encountered index i. If for current index i, nums[i] already exist in the hashtable, then we can extract the current index i and previous index i whose values sum to target, and return them. It will become clear in the following steps.</p><ol><li>We implement a hashtable using a python defaultdict named cache with all default values as None. For more information on defaultdict, <a href="https://www.geeksforgeeks.org/defaultdict-in-python/">see here</a>.</li><li>We use a loop to iterate through all indexes i in the array.</li><li>If the value of nums[i] in the hashtable is not None, then we have found our pair. We return i and cache[nums[i]].</li><li>Otherwise, we find the difference between the target sum and the current nums[i]. We assign value of cache[diff]=i.</li></ol><pre>class Solution:<br>    def twoSum(self, nums: List[int], target: int) -&gt; List[int]:<br>        cache=defaultdict(lambda:None)<br>        for i in range(0,len(nums)):<br>            if cache[nums[i]] is not None:<br>                return list([cache[nums[i]],i])<br>            diff=target-nums[i]<br>            cache[diff]=i</pre><p>Time = O(N) and Space = O(1)</p><h3>167. Two Sum II — Input Array Is Sorted</h3><p>Question — <a href="https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/">https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/</a></p><p>Difficulty — Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mGPHiW_vKfHZKVp96_j5w.png" /></figure><p><strong>Brute Force and Hashing Solution —</strong></p><p>Same as the solution of Two Sum.</p><p><strong>Two Pointer Approach —</strong></p><p>We can reduce the time complexity by avoiding nested loops.</p><p>Since we are given a sorted array, the first element will be the smallest and the last element will be the greatest value. Moving to the right will increase value and moving to the left will decrease value. We can use two pointers each starting from index 0 and index n-1 for the two elements and then move them left or right based on the current and target sum relationship.</p><pre>class Solution:<br>    def twoSum(self, nums: List[int], target: int) -&gt; List[int]:<br>        n=len(nums)<br>        i,j=0,n-1<br>        while i&lt;j:<br>            if nums[i]+nums[j]==target:<br>                return list([i,j])<br>            elif nums[i]+nums[j]&lt;target:<br>                i+=1<br>            else:<br>                j-=1</pre><p>Time = O(N logN) and Space = O(1)</p><h3>2006. Count Number of Pairs With Absolute Difference K</h3><p>Question — <a href="https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/">https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/</a></p><p>Difficulty — Easy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9I6PzKE1icmDRk_SKd9kZQ.png" /></figure><p><strong>Brute Force —</strong></p><p>Use two nested loops to check the absolute difference for each pair and increment count when the difference is equal to k. But this will take Quadratic Time O(N²).</p><p><strong>Hashing Solution —</strong></p><p>This is similar to the hashing solution in Two Sum.</p><ol><li>We iterate through the array once and use a hash table to keep a count of the number of occurrences of each value.</li><li>We iterate again and this time for each value we find if value+k has occurred. If it has then we increment our pair counter by (no. on occurrences of value)*(no. of occurrences of value+k), which is the number of distinct pairs possible by these values.</li></ol><pre>class Solution:<br>    def countKDifference(self, nums: List[int], k: int) -&gt; int:<br>        cache={}<br>        count=0<br>        for i in nums:<br>            if i in cache:<br>                cache[i]+=1<br>            else:<br>                cache[i]=1<br>        for i in cache:<br>            if i+k in cache:<br>                count+=cache[i]*cache[i+k]<br>        return count</pre><p>Time = O(N) and Space = O(N)</p><h3>2200. Find All K-Distant Indices in an Array</h3><p>Question — <a href="https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/">https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/</a></p><p>Difficulty — Easy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZG5gvvKW9xWUF21rWHhkQ.png" /></figure><p><strong>Using Set —</strong></p><ol><li>We iterate through the array and whenever we find an index i where nums[i] is key, we append all values in [i-k,i+k] which are more than or equal to 0 and less than the length of the array to our solution list.</li><li>We convert the solution list to a set and then back to a list and return it. Conversion to set removes all duplicates from the list.</li></ol><pre>class Solution:<br>    def findKDistantIndices(self, nums: List[int], key: int, k: int) -&gt; List[int]:</pre><pre>n=len(nums)<br>        nodes=[]<br>        for i in range(0,n):<br>            if nums[i]==key:<br>                nodes+=[x for x in range(i-k,i+k+1) if x&gt;=0 and x&lt;n]<br>        return list(set(nodes))</pre><p>Time = O(N²) and Space = O(N)</p><p><strong>Without Set —</strong></p><p>The interviewer might require us to implement the same algorithm without using the features of a python set.</p><p>We can do this by using a list to store the number of occurrences of each value and then append indexes to the solution list which have a value&gt;0 in the list.</p><pre>class Solution:<br>    def findKDistantIndices(self, nums: List[int], key: int, k: int) -&gt; List[int]:</pre><pre>n=len(nums)<br>        nodes=[0]*n<br>        ans=[]</pre><pre>for i in range(0,n):<br>            if nums[i]==key:<br>                for x in range(i-k,i+k+1):<br>                    if x&gt;=0 and x&lt;n:<br>                        nodes[x]+=1</pre><pre>for i in range(n):<br>            if nodes[i]&gt;0:<br>                ans.append(i)</pre><pre>return ans</pre><p>Time = O(N²) and Space = O(N)</p><p><strong>Space Optimised Solution without Set —</strong></p><p>We can reduce the need for an extra array to store occurrences if we check one additional condition while adding indices to the solution array. Along with checking if x≥0 and x&lt;n, we also check if either solution array is empty or x&gt;nodes[-1]. Overlapping indices will not be added to the solution.</p><pre>class Solution:<br>    def findKDistantIndices(self, nums: List[int], key: int, k: int) -&gt; List[int]:<br>        n=len(nums)<br>        nodes=[]<br>        for i in range(0,n):<br>            if nums[i]==key:<br>                for x in range(i-k,i+k+1):<br>                    if x&gt;=0 and x&lt;n and (len(nodes)==0 or x&gt;nodes[-1] ):<br>                        nodes.append(x)<br>        return nodes</pre><p>Time = O(N²) and Space = O(N)</p><p>Space complexity is the same but here we are not requiring two arrays, only one solution array.</p><h3>15. 3Sum</h3><p>Question — <a href="https://leetcode.com/problems/3sum/">https://leetcode.com/problems/3sum/</a></p><p>Difficulty — Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTpDbKtHVx-J0f4yfBAQnQ.png" /></figure><p><strong>Brute Force —</strong></p><p>Use three nested loops to find and compare all possible triplets. But this method will have a cubic time complexity O(N³).</p><p><strong>Optimised Solution —</strong></p><p>For this problem, we will reuse the solution of Two Sum II.</p><pre>class Solution:<br>    def threeSum(self, nums: List[int]) -&gt; List[List[int]]:<br>        <br>        n=len(nums) <br>        nums.sort()<br>        ans=[]</pre><pre>for k in range(len(nums)):<br>            if k==0 or nums[k]!=nums[k-1]:<br>                i,j=k+1,n-1</pre><pre>while i&lt;j:<br>                    if nums[i]+nums[j]+nums[k]==0:<br>                        if [nums[k],nums[i],nums[j]] not in ans:<br>                            ans.append([nums[k],nums[i],nums[j]])<br>                        i+=1<br>                    elif nums[i]+nums[j]+nums[k]&lt;0:<br>                        i+=1<br>                    else:<br>                        j-=1<br>        return ans</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67135a13d825" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stock Price Questions —Arrays,  Greedy, DP]]></title>
            <link>https://medium.com/@dayita.chaudhuri/all-stock-price-questions-on-leetcode-ccf474de921e?source=rss-a334f21539c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccf474de921e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Dayita Chaudhuri]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 09:33:35 GMT</pubDate>
            <atom:updated>2023-11-03T15:59:33.233Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stock Price Questions on Leetcode— Arrays, Greedy, DP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DENauUixUf2DS-VfgKCXlA.png" /></figure><p>The beauty of the stock price problems is that these six correlated questions cover a variety of different topics ranging from simple arrays to dynamic programming methodologies, and these have a number of different ways to solve them. I will try to tackle as many approaches as possible, but if anything is left, please comment down below.</p><p><strong>Contents —</strong></p><ol><li>Best Time to Buy and Sell Stock</li><li>Best Time to Buy and Sell Stock II</li><li>Best Time to Buy and Sell Stock III</li><li>Best Time to Buy and Sell Stock IV</li><li>Best Time to Buy and Sell Stock with Cooldown</li><li>Best Time to Buy and Sell Stock with Transaction Fee</li></ol><h3>121. Best Time to Buy and Sell Stock</h3><p>Question — <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">https://leetcode.com/problems/best-time-to-buy-and-sell-stock/</a></p><p>Difficulty — Easy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*I6SDcVbdj2H48ayGN1v_aA.png" /></figure><p><em>To Note — We can only make one transaction.</em></p><blockquote><strong>Brute Force —</strong></blockquote><ol><li>For each value prices[i], find the largest value of prices[j] to the right of i, ie j&gt;i.</li><li>Buy at prices[i] and sell at prices[j]. If profit is more than maxProfit, update maxProfit.</li></ol><pre>class Solution:<br>    def maxProfit(self, prices: List[int]) -&gt; int:</pre><pre>        prof=0</pre><pre>        for i in range(0,len(prices)-1):<br>            buy=prices[i]<br>            sell=prices[i+1]<br>            for j in range(i+1,len(prices)):<br>                if prices[j]&gt;sell:<br>                    sell=prices[j]<br>            if sell-buy&gt;prof:<br>                prof=sell-buy</pre><pre>        return prof</pre><p>Time = O(N²) and Space = O(N)</p><blockquote><strong>Better Approach (Single Pass)—</strong></blockquote><p>The logic is that we need to find i and j such that i&lt;j and (prices[j]-prices[i]) is maximised. And we need to do this in a single pass.</p><ol><li>We initialise buy as prices[0] and prof = 0.</li><li>We iterate the prices list.</li><li>If the price becomes less than the price we bought at, we buy at the current price.</li><li>If the price becomes more than the price we bought at, we check if selling at the current price will give a profit more than maxProfit. If yes then we sell and update maxProfit.</li></ol><pre>class Solution:<br>    def maxProfit(self, prices: List[int]) -&gt; int:<br>        <br>        buy = prices[0]<br>        profit = 0<br>        <br>        for i in range(0,len(prices)):<br>            &#39;&#39;&#39;If price is less than the price we were buying at, <br>            we change our buy to the current price.&#39;&#39;&#39;<br>            if prices[i] &lt; buy:<br>                buy = prices[i]<br>                <br>            &#39;&#39;&#39;If price has increased, we check if selling at current <br>            price will give us a profit more than prof.&#39;&#39;&#39;<br>            elif prices[i] - buy &gt; prof:<br>                profit = prices[i] - buy<br>                <br>        return prof</pre><p>Time = O(N) and Space = O(1)</p><blockquote><strong>Video Explanation —</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBSRTUtvJSIk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBSRTUtvJSIk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBSRTUtvJSIk%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/1450cfc283f75028fc26f10552e3dcec/href">https://medium.com/media/1450cfc283f75028fc26f10552e3dcec/href</a></iframe><h3>122. Best Time to Buy and Sell Stock II</h3><p>Question — <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/">https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/</a></p><p>Difficulty — Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*lFnQPKr83EYuM5DXUquqrw.png" /></figure><p><em>Please go through all approaches to this problem as it will lead to solutions to all future problems as well.</em></p><blockquote><strong>Continuation from previous One Pass Solution —</strong></blockquote><p>Consider the array like a line graph. There are ups and downs simultaneously. Our maximum profit will be achieved if we can take all the ups. At each lowest dip, we buy the stock, and at each highest peak, we sell the stock at hand.</p><ol><li>When the graph goes low and we have stock, we sell.</li><li>When the graph goes high and we do not have stock, we buy stock.</li></ol><pre>class Solution:<br>    def maxProfit(self, prices: List[int]) -&gt; int:<br>        <br>        low=high=prices[0]<br>        prof=0<br>        <br>        for i in range(1,len(prices)):<br>            <br>            <strong>#  If price goes up, update selling point.</strong><br>            if prices[i]&gt;prices[i-1]:<br>                high=prices[i]<br>                <br>           <strong> # If prices goes down, add current profit to total  <br>            profit and update both buying and selling points.</strong><br>            else:<br>                prof+=high-low<br>                high=low=prices[i]<br>                <br>        <strong># To tackle edge case where array ends in high, add <br>        remaining profit to total profit, and return profit.</strong><br>        prof+=high-low</pre><pre>        return prof</pre><p>Time = O(N) and Space = O(1)</p><blockquote><strong>Greedy Solution —</strong></blockquote><ol><li>It is an optimisation problem.</li><li>The total maximum profit will contain the maximum profit for any subsection (Optimal Substructure).</li></ol><p>Hence we can solve this using Greedy Algorithm. For each time unit (i and i+1), if prices[i+1]&gt;prices[i], we will take the profit. This will ultimately give us the final maximum profit.</p><pre>class Solution:<br>    def maxProfit(self, prices: List[int]) -&gt; int:</pre><pre>        prof=0<br>        for i in range(1,len(prices)):<br>            if prices[i]&gt;prices[i-1]:<br>                prof+=prices[i]-prices[i-1]</pre><pre>        return prof</pre><p>Time = O(N) and Space = O(1)</p><p>Though it has no real advantage over the previous in terms of complexity, it is easier to code and understand.</p><p><strong><em>NOTE :</em></strong></p><p><em>Since this is a classic optimisation problem, </em><strong><em>Dynamic Programming</em></strong><em> can be applied here. Using DP here is unnecessary but the DP Solutions I am mentioning below need to be studied as these will be reused in the next two questions with very minor changes.</em></p><blockquote><strong>Recursive Solution —</strong></blockquote><p>We can create a decision tree and observe the possible choices. At each step, we have two choices, either to wait for the step out or to do an action. The action depends on whether or not we are holding stock.</p><ul><li>If we are not holding stock, we can either buy stock or wait.</li><li>If we are holding stock, we can either sell stock or wait.</li></ul><p>We choose whatever gives us maximum profit in the end.</p><p>i → index, hold → whether we are holding stock or not.</p><pre>class Solution:<br>    def maxProfit(self, prices: List[int]) -&gt; int:<br> <br>        n = len(prices)<br>        <br>        def dfs(i,hold):</pre><pre>            if i&gt;=n:<br>                return 0<br>            if hold:<br>               return max(dfs(i+1,not hold)+prices[i],dfs(i+1,hold))  <br>            else:<br>               return max(dfs(i+1,not hold)-prices[i],dfs(i+1,hold))<br>    <br>        return dfs(0,False)</pre><p>Time = O(N²) and Space = O(N)</p><p>This will give TLE.</p><blockquote><strong>Dynamic Programming Solution (Memoization/Top-Down) —</strong></blockquote><p>From the recursive solution, we found that —</p><ul><li>If we are not holding stock, we can either buy stock or wait.</li><li>If we are holding stock, we can either sell stock or wait.</li></ul><p>We choose whatever gives us maximum profit in the end.</p><p>To store our results, we will use a hashmap that will have key as (i, hold). Hold will be True or False depending on whether we are holding stack. We will start from i=0 and hold=False. The final returned value will be our maximum profit.</p><pre>class Solution:<br>    def maxProfit(self, prices: List[int], fee: int) -&gt; int:<br>        <br>        n = len(prices)<br>        dp = {}<br>        <br>        def dfs(i,hold):<br>            <br>            <strong># Base Cases</strong><br>            if i&gt;=n:<br>                return 0<br>            if (i,hold) in dp:<br>                return dp[(i,hold)]<br>            <br>            <strong># If holding stock, we can sell it or wait.</strong><br>            if hold:<br>                dp[(i,hold)] = max(dfs(i+1,not hold) + prices[i], dfs(i+1,hold))<br>                <br>            <strong># If not holding stock, we can either buy it or wait.</strong><br>            else:<br>                dp[(i,hold)] = max(dfs(i+1,not hold) - prices[i], dfs(i+1,hold))<br>                <br>            return dp[(i,hold)]<br>    <br>        return dfs(0,False)</pre><p>Time = O(2N) = O(N)</p><p>Space = O(N) for hashmap +O(N) for recursion = O(2N) = O(N)</p><blockquote><strong>Dynamic Programming Approach (Tabulation/Bottom-Up) —</strong></blockquote><p>The same algorithm can be implemented using tabulation. Here instead of a hashmap, I am using a matrix to store the results.</p><p>dp[i][1] — dp[(i, True)] → Action = Sell</p><p>dp[i][0] — dp[(i, False)] → Action = Buy</p><p>Code :</p><pre>class Solution:<br>    def maxProfit(self, prices: List[int]) -&gt; int:<br>        <br>        dp=[[0,0] for i in range(0,len(prices)+2)]<br>        <br>        for i in range(len(prices)-1,-1,-1):<br>            <br>            <strong># For Hold=False, max(buy,wait)</strong><br>            dp[i][0]=max(dp[i+1][1]-prices[i],dp[i+1][0])<br>            <br>            <strong># For Hold=True, max(sell,wait)</strong><br>            dp[i][1]=max(dp[i+1][0]+prices[i],dp[i+1][1])<br>        <br>        return dp[0][0]</pre><p>Time = O(N) and Space = O(N)</p><h3>309. Best Time to Buy and Sell Stock with Cooldown</h3><p>Question — <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/">https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/</a></p><p>Difficulty — Medium</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*65YKmJ-c2t1N8CWcqXN9fQ.png" /></figure><p>Here the main difference is that we cannot sell and buy on consecutive days. After selling we need to wait for one day before we enter the market again.</p><p>It is an optimisation problem. But this problem cannot be solved by Greedy approach. We will make a very minor change to the DP Solutions we saw in the last question and solve this one.</p><p><strong>NOTE :</strong></p><p><em>The only change is that in here when we sell, we will move i to i+2.</em></p><blockquote><strong>Dynamic Programming Approach (Memoization/Top-Down)—</strong></blockquote><p>We can create a decision tree and observe the possible choices. At each step, we have two choices, either to wait for the step out or to do an action. The action depends on whether or not we are holding stock.</p><p>If we are not holding stock, we can either —</p><ol><li>Buy stock. Spend prices[i]. Move to i+1.</li><li>Wait for the round and move to i+1.</li></ol><p>If we are holding stock, we can either —</p><ol><li>Sell stock. Earn prices[i]. Wait for a round and <strong>move to i+2</strong>.</li><li>Wait for the round and move to i+1.</li></ol><p>We choose whatever gives us maximum profit in the end.</p><p>We will use a hashmap that will have key as (i, hold). Hold will be True or False depending on whether we are holding stack. We will start from i=0 and hold=False. The final returned value will be our maximum profit.</p><p>Code :</p><pre>class Solution:<br>    def maxProfit(self, prices: List[int]) -&gt; int:<br>        <br>        n = len(prices)<br>        dp = {}<br>        <br>        def dfs(i,hold):<br>            <br>            <strong># Base Cases</strong><br>            if i&gt;=n:<br>                return 0<br>            if (i,hold) in dp:<br>                return dp[(i,hold)]<br>            <br>            <strong># If holding stock, we can sell it and wait the coldown.</strong><br>            if hold:<br>                action = dfs(i+2,not hold) + prices[i]<br>                <br>            <strong># If not holding stock, we can buy it.</strong><br>            else:<br>                action = dfs(i+1,not hold) - prices[i]<br>                <br>            <strong># We can wait.</strong><br>            wait = dfs(i+1, hold)<br>            <br>            <strong># Update the hashmap with maximum of selling/buying and <br>            waiting.</strong><br>            dp[(i,hold)] = max(action,wait)<br>            return dp[(i,hold)]<br>    <br>        return dfs(0,False)</pre><p>Time = O(2N) = O(N)</p><p>Space = O(N) for hashmap + O(N) for Recursion = O(2N) = O(N)</p><blockquote><strong>Dynamic Programming Approach (Tabulation/Bottom-Up) —</strong></blockquote><p>The same algorithm can be implemented using tabulation. Here instead of a hashmap, I am using a matrix to store the results.</p><p>dp[i][1] — dp[(i, True)] → Action = Sell</p><p>dp[i][0] — dp[(i, False)] → Action = Buy</p><p>Code :</p><pre>class Solution:<br>    def maxProfit(self, prices: List[int]) -&gt; int:<br>        <br>        dp=[[0,0] for i in range(0,len(prices)+2)]<br>        <br>        for i in range(len(prices)-1,-1,-1):<br>            <br>            <strong># For Hold=False, max(buy,wait)</strong><br>            dp[i][0]=max(dp[i+1][1]-prices[i],dp[i+1][0])<br>            <br>            <strong># For Hold=True, max(sell,wait)</strong><br>            dp[i][1]=max(dp[i+2][0]+prices[i],dp[i+1][1])<br>        <br>        return dp[0][0]</pre><p>Time = O(N) and Space = O(N)</p><h3>714. Best Time to Buy and Sell Stock with Transaction Fee</h3><p>Question — <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/s">https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/</a></p><p>Difficulty — Medium</p><p>This is very similar to Best Time to Buy and Sell Stock II and we will make a very minor change to the DP Solution we saw there.</p><p><strong>NOTE :</strong></p><p><em>The only change is that in here when we sell, we deduct the transition fee along with adding prices[i].</em></p><blockquote><strong>Dynamic Programming Approach (Memoization/Top-Down) —</strong></blockquote><p>We can create a decision tree and observe the possible choices. At each step, we have two choices, either to wait for the step out or to do an action. The action depends on whether or not we are holding stock.</p><ul><li>If we are not holding stock, we can either buy stock or wait.</li><li>If we are holding stock, we can either sell our stock and <strong>pay the transaction fee</strong>, or wait.</li></ul><p>We choose whatever gives us maximum profit in the end.</p><p>We will use a hashmap that will have key as (i, hold). Hold will be True or False depending on whether we are holding stack. We will start from i=0 and hold=False. The final returned value will be our maximum profit.</p><p>Code :</p><pre>class Solution:<br>    def maxProfit(self, prices: List[int], fee: int) -&gt; int:<br>        <br>        n = len(prices)<br>        dp = {}<br>        <br>        def dfs(i,hold):<br>            <br>            <strong># Base Cases</strong><br>            if i&gt;=n:<br>                return 0<br>            if (i,hold) in dp:<br>                return dp[(i,hold)]<br>            <br>            <strong># If holding stock, we can either sell it with <br>            transaction fee or wait.</strong><br>            if hold:<br>                dp[(i,hold)] = max(dfs(i+1,not hold) + prices[i] - fee, dfs(i+1,hold))<br>                <br>            <strong># If not holding stock, we can either buy it or wait.</strong>             <br>            else:<br>                dp[(i,hold)] = max(dfs(i+1,not hold) - prices[i], dfs(i+1,hold))<br>                <br>            return dp[(i,hold)]<br>    <br>        return dfs(0,False)</pre><p>Time = O(2N) = O(N)</p><p>Space = O(N) for hashmap + O(N) for Recursion = O(2N) = O(N)</p><blockquote><strong>Dynamic Programming Approach (Tabulation/Bottom-Up) —</strong></blockquote><p>The same algorithm can be implemented using tabulation. Here instead of a hashmap, I am using a matrix to store the results.</p><p>dp[i][1] — dp[(i, True)] → Action = Sell</p><p>dp[i][0] — dp[(i, False)] → Action = Buy</p><p>Code :</p><pre>class Solution:<br>    def maxProfit(self, prices: List[int], fee: int) -&gt; int:<br>        <br>        dp=[[0,0] for i in range(0,len(prices)+2)]<br>        <br>        for i in range(len(prices)-1,-1,-1):<br>            <br>            <strong># For Hold=False, max(buy,wait)</strong><br>            dp[i][0]=max(dp[i+1][1]-prices[i],dp[i+1][0])<br>            <br>            <strong># For Hold=True, max(sell,wait)</strong><br>            dp[i][1]=max(dp[i+1][0]+prices[i]-fee,dp[i+1][1])<br>        <br>        return dp[0][0]</pre><p>Time = O(N) and Space = O(N)</p><blockquote><strong>Without Extra Space —</strong></blockquote><pre>class Solution:<br>    def maxProfit(self, prices: List[int], fee: int) -&gt; int:<br>        cost=-prices[0]<br>        sell=0<br>        for i in range(1,len(prices)): <br>            cost=max(cost,sell-prices[i])<br>            sell=max(sell,prices[i]+cost-fee)<br>        return sell</pre><p>Time = O(N) and Space = O(1)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccf474de921e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>