<?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[Leetcode Patterns - Medium]]></title>
        <description><![CDATA[The motive of the articles published here would be to decode common patterns used to solve algorithm problems and gain a clear intuition to how these work. - Medium]]></description>
        <link>https://medium.com/leetcode-patterns?source=rss----239b747456f4---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Leetcode Patterns - Medium</title>
            <link>https://medium.com/leetcode-patterns?source=rss----239b747456f4---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 11 Nov 2026 23:09:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/leetcode-patterns" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Leetcode Patterns : Checkpoint 0]]></title>
            <link>https://medium.com/leetcode-patterns/leetcode-patterns-checkpoint-0-b83ab2bb3170?source=rss----239b747456f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/b83ab2bb3170</guid>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[csgator]]></dc:creator>
            <pubDate>Fri, 20 Sep 2019 23:09:00 GMT</pubDate>
            <atom:updated>2019-09-20T23:09:00.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode Patterns : Checkpoint 0</h3><p>Hi there! It’s been so long since my last post and my life has undergone so many changes during these past few months :), it’s insane! The one constant that remains is people reading these blogs and reaching out to me on LinkedIn to provide feedback, it makes my day!</p><p>I graduated from university, started a new job, shifted all the way from Florida to Bay Area (finally woohoo!), moved into a new house, it was crazy!</p><p>So I wanted to pause for a moment and look back, provide some context on why I started the blog, what it means to me and some plans I have to extend the blog, now that I am all settled in.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FB5xUYIuk794%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DB5xUYIuk794&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FB5xUYIuk794%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/698c4ed0e7d6a15121fb749e57eb4531/href">https://medium.com/media/698c4ed0e7d6a15121fb749e57eb4531/href</a></iframe><p>Please provide feedback in the comments section of the video. If you’re in bay area and would like schedule a coffee chat send me a ping, Thanks!</p><p>-<a href="https://www.linkedin.com/in/csgator/">csgator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b83ab2bb3170" width="1" height="1" alt=""><hr><p><a href="https://medium.com/leetcode-patterns/leetcode-patterns-checkpoint-0-b83ab2bb3170">Leetcode Patterns : Checkpoint 0</a> was originally published in <a href="https://medium.com/leetcode-patterns">Leetcode Patterns</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Pattern 4 | Meta Stuff]]></title>
            <link>https://medium.com/leetcode-patterns/leetcode-pattern-4-meta-stuff-4ebbbef7d4c0?source=rss----239b747456f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/4ebbbef7d4c0</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[csgator]]></dc:creator>
            <pubDate>Mon, 29 Oct 2018 08:53:49 GMT</pubDate>
            <atom:updated>2018-10-29T09:35:53.079Z</atom:updated>
            <content:encoded><![CDATA[<p>So this article is a bit different from the other ones in this series and it’s not about specific algorithms but the general approach one should try to follow in their leetcode journey. This is based on my own personal experiences and what I have gathered talking to people who got multiple big-N job offers after a good amount of leetcoding. I think this article would be by far the most important one as it touches on the meta stuff that not a lot of people talk about.</p><h4><strong>Problem Solving Approach</strong></h4><p>Think about the problem for at least 30 minutes and put in your best efforts to solve the problem on your own. Think through the test cases, imagine how you would be writing code and write the code without IDE. Try to minimize the use of a compiler. It’s important to write bug-free code without using a compiler for big N companies. I’ll explain below why I mention these very specific points ( some of which might have freaked you out ).</p><h4>Why the 30-minute mark?</h4><p>The thinking part is really important, can’t emphasize this enough! I didn’t have a lot of patience early on and would just try to optimize the number of problems seen over learning. I would look up solutions after 10 minutes of sloppy efforts. After a few times of doing this, I wouldn’t think at all and would just reach out for the discuss tab.</p><p>There is a bit of learning that can happen through this process but there is a huge loss too. For example, I was asked the <a href="https://leetcode.com/problems/meeting-rooms-ii/">meeting rooms</a> problem in an interview (it is a frequently asked problem in one of the FAANG’s! ) and instead of thinking about the problem at hand I would try to retrieve the solution from the buggy in-memory hashtable I built over time.</p><p>The more you struggle with a problem the more you’ll learn after seeing the solution and best case is if you look at the solution after solving it on your own. Try to improve your thinking abilities, because it’s very likely that when you face the same problem weeks later you’ll not remember the solution and you’ll most definitely think in a similar way you did the first time. So if you learned the paradigm required to solve that problem and solved a lot of other similar problems using that strategy you’ll actually be able to solve it later.</p><p>The worst part is it’s hard to realize if this is happening subconsciously, so as a litmus test I would say try resolving random problems from past practice after a set amount of time. Spaced repetition also helps consolidate your learnings ( <a href="https://www.firecode.io/">firecode.io</a> is popular because of this very fact )</p><p>In real life, there is always a time constraint, interviews coming up, limited time available in the day due to coursework, and so many patterns to learn which is why it’s a tradeoff and I suggested the 30-minute limit, you could play with it depending on how much time you have at hand. You need to realize that it’s not about the number of problems you solved before an interview but if you are able to apply your learnings to a new problem in an interview setting.</p><p>Don’t think that you need to solve all problems on leetcode that would be crazy and if you do it the correct way you won’t need to solve more than 300–400 problems to be confident for a full-time interview, 150 for internships with a good balance of mediums , few hards and fewer easy ( a realistic average case figure, not talking about outliers who only did 70 lc problems to land a big N offer ). Most problems are repetitive anyway, same logic applied with a 1–2 line change. Focus on learning core paradigms ( DP, graphs, backtracking, trees, etc )</p><p>It is fine if you’re not able to solve a problem but it is important that you’re able to solve a similar problem after absorbing the approach for the current problem.</p><h4><strong>Test your code</strong></h4><p>In a real interview you would tell your approach to the interviewer and if he/she is satisfied with your approach you’ll be writing code, then the interviewer would likely ask you the time and space complexities and finally many interviewers ask you to write test cases. It’s hard to do TDD ( test driven development) and only the people who train themselves to do so can replicate that in interviews. So in my case, I would write code then write/think about test cases later.</p><p>But the best programmers I’ve seen would go through the test cases first to arrive at an approach. The code they write will cover the corner cases too cause they thought through the test cases first and interviewers are generally impressed with that approach. It also helps us to make sure that we understood the problem correctly and I could go on and on, just write/think through test cases first if possible :), if not at least do so before submitting your code. Avoid doing this: click submit, get WA ( wrong answer) fix failing test case, repeat loop until an AC ( accepted ) that’s a really crappy thing to do and TDD would likely help you avoid it.</p><h4>Why not use an IDE?</h4><p>That’s totally up to you but I suggested so because many people are so IDE dependent that they are practically crippled if someday they had to write code using notepad. Google interviews take place in google docs and I understand the principles behind this weird decision. If you are really good at the language you code in and have used it to for a while, you tend to internalize the language. If you let go of the over usage of IDEs and language references you’ll most likely become a better programmer but that’s debatable so I’ll leave it at that.</p><h4>Definitely reduce compiler usage!!</h4><p>Why? because when you restrict yourself to not use the compiler, you read through your code and try to mentally compile it, spotting logic and syntax errors on your own. With enough practice, you don’t even make those errors and you tend to code faster. That to me is a sign of a good programmer and interviews are all about getting signals if you are good enough for the job :). This is not a strict requirement but I would say it’s good to set high standards for yourself and get out of your comfort zone.</p><p>Facebook interviewers look for this skill ( conclusion based on limited data points ) and most interviewers are sharp enough to look at your code and tell you where your bugs are. Can you spot and fix those bugs without compiling?</p><h4>General tips</h4><p>Do look at solutions posted in discuss after solving the problem or if you’re stuck. You’ll learn a lot by going through a few solutions, probably learn different styles of writing the same thing or learn different approaches all together. Leetcode discuss is gold and I attribute most of my learnings to discuss. Maintain a github repo where you could keep adding your solutions, an active github chart looks good to whoever visits your profile!</p><p>Don’t look at problem tags until you are stuck! that’s part of the problem-solving process to figure out what category the problem falls into. Alternatively to get good at a specific paradigm pick problems from that tag and keep solving until you get comfortable. It’s a mix of these two opposite approaches being applied alternatively that’ll set you up for success in your big N interview.</p><p>Maintain a google doc / excel sheet or use leetcode notes feature where you record why you couldn’t solve it, what you learned through that problem, time to get AC including time to write code, time spent to think, number of times you clicked run code, number of submissions to get AC, etc. Such statistical analysis will definitely improve your skills over time.</p><h4>Leetcode contests for the win!</h4><p>I highly recommend doing contests every Saturday, because you’ll be trying to code faster as it is timed and there is a ranking system based on how quickly you get AC and penalties for buggy submissions. After doing enough contests you’ll rise in ranks, improve your rating and it’ll give you an adrenaline rush to keep going. They also post official solutions after a few hours which are nicely written. Most leetcode contest problems were popular interview questions in the time period the contest was conducted so definitely do contests regularly :)</p><p>Lesser known fact, if you do well in leetcode contests some companies will directly contact you for an interview. If you get a rank within 200 ( possible with enough practice on leetcode) that’s definitely worth mentioning on your resume as well.</p><h4>Applying</h4><p>At one point you’ll realize that you’re comfortable with solving problems but if you don’t get interviews you won’t land your big N job. This topic deserves its own article but here’s the gist:</p><ol><li>Resume format doesn’t matter much but the content is what matters. Keep it simple and readable, no colors or logos. Use careercup’s simple template and worship this <a href="https://www.careercup.com/resume">article</a>, IT WORKS!</li><li>Always apply through referrals and don’t think that your network is limited, use LinkedIn the right way and make connections. Most people will refer you if you’re good enough cause it feels good to help a person out and also that referral bonuses are huge. It’s a win-win situation for the company avoiding high recruiting agency costs, you and the person who refers you, think about it!</li><li>Follow point 1 and shoot your resumes to recruiters on LinkedIn or email. Many recruiters are actively looking for candidates on LinkedIn. I got my Uber interview after I contacted a recruiter directly.</li><li>Brands definitely matter, so once you get that big N internship/work experience it’s really easy to get interviews, otherwise highlight your personal projects, course projects, open source experience, hackathon wins, whatever convinces a person in one glance that you are worth giving an interview/referral at least.</li></ol><p>Point 4 is all about getting signals if you are good enough as a developer so whatever you can do to prove to the world that you’re good enough. In my case, I didn’t have any work experience so I wrote articles about solving algorithm problems and shared them on Linkedin :). I had GSoC on my resume which was an important factor and I put my personal projects on top. Keep experimenting with your resume format until it works and you get interviews.</p><p>People complain that they applied for 400+ jobs online and got no callbacks. It doesn’t matter how many jobs you applied to, a more realistic statistic is to consider how many interviews you had ( through whatever, cold emails, referrals, online apps ). Applying online is like brute force, you can’t say you brute forced enough but are still getting a TLE, come up with smarter approaches to beat the crowd.</p><p>Thanks for reading so far, you’re awesome! That’s it for this article and I’ll end it with something that I had on my mind for a long time.</p><h4>Youtube Channel</h4><p>I’ve always wanted to make algorithm tutorials. Over time I’ve come to like algorithms and leetcoding is no longer an activity I pursue to get a good job. It is something I do out of my own interest, which I consider to be the best reason to do something, allows you to get really good at that thing with lower effort. Now that I have a job lined up and lighter course load I have a lot of time on my hands to actually work on this project.</p><p>More specifically I want a low effort thing where I can help people get good at leetcode style problems and understand core algorithms. I am a big fan of youtube, it is the primary activity of my day and I realize the kind of effort that goes into recording and editing videos. I plan to stick with simple screencasts and a whiteboard where I could explain an algorithm and solve a few leetcode problems using that algorithm.</p><p>Why low effort ? because I would be able to keep doing it in a sustained manner, meaning more content produced overall and more topics covered. In the past, I’ve received a lot of positive feedback for this series and I would love to continue this but it’s a lot of effort to write articles and it’s easier to convey information in the form of video. I am trying to measure interest in this project so please do leave a comment or send me a message on LinkedIn to let me know what you think about this :)</p><p>Fun facts :</p><ol><li>I never had taken a formal algorithms course until this semester and my undergrad was in Electronics.</li><li>Leetcode’s founder Winston Tang had developed the website for his own use while he was prepping for interviews.</li><li>Never gets old -&gt; <a href="https://www.youtube.com/watch?v=wZR6QFE2m6o">https://www.youtube.com/watch?v=wZR6QFE2m6o</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ebbbef7d4c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/leetcode-patterns/leetcode-pattern-4-meta-stuff-4ebbbef7d4c0">Leetcode Pattern 4 | Meta Stuff</a> was originally published in <a href="https://medium.com/leetcode-patterns">Leetcode Patterns</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Pattern 3 | Backtracking]]></title>
            <link>https://medium.com/leetcode-patterns/leetcode-pattern-3-backtracking-5d9e5a03dc26?source=rss----239b747456f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/5d9e5a03dc26</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[csgator]]></dc:creator>
            <pubDate>Thu, 22 Feb 2018 03:51:48 GMT</pubDate>
            <atom:updated>2018-02-22T03:54:45.532Z</atom:updated>
            <content:encoded><![CDATA[<p>A very important tool to have in our arsenal is backtracking, it is all about knowing when to stop and step back to explore other possible solutions. In today’s post we’ll explore the common pattern in solving backtracking problems and set up the stage to dive into dynamic programming (DP) problems next. It is amusing how a small change in the problem can change the solution from DP to backtracking and understanding this will help us save time.</p><p>Backtracking can be seen as an optimized way to brute force. Brute force approaches evaluate every possibility. In backtracking you stop evaluating a possibility as soon it breaks some constraint provided in the problem, take a step back and keep trying other possible cases, see if those lead to a valid solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*De1V_tw93TN3gwLyB0SH7Q.jpeg" /></figure><p>So in fact, it’s kinda like a depth-first search(DFS) with an added constraint that we stop exploring the subtree as soon as we know for sure that it won’t lead to valid solution. The problems that can be solved using this tool generally satisfy the following criteria :</p><ol><li>You are explicitly asked to return a collection of all answers.</li><li>You are concerned with what the actual solutions are rather than say the most optimum value of some parameter. (if it were the latter it’s most likely DP or greedy).</li></ol><h4><a href="https://leetcode.com/problems/subsets/description/">78. Subsets</a></h4><p>We’ll use this problem to get familiar with the recursive backtracking pattern.</p><p>The problem is to find the powerset of a given set, so we simply need to collect all possible subsets of a set. This could be done in a variety of ways and backtracking is one way to go, also since there are no constraints provided we simply explore all cases (all subsets).</p><p>A subset can either have an element or leave it out giving rise to 2^n subsets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/839d184f196b2823e65e7010615f599b/href">https://medium.com/media/839d184f196b2823e65e7010615f599b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddhF2JWfmEl8yLwjx5vt7Q.jpeg" /></figure><p>Take a moment to absorb the magic happening in the loop and that’s everything you’ll ever need to solve a backtracking problem. It was confusing to me at first but it’s an amazing pattern. Drawing the flow of the recursive function helped me wrap my head around what is going on.</p><p>Also here is my alternative solution to the same problem which uses the partially formed output to generate the full output incrementally. It’s basically deriving the complete solution from solutions of smaller problems, does it ring a bell?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/043113ee69caff850d44b9a30750aac1/href">https://medium.com/media/043113ee69caff850d44b9a30750aac1/href</a></iframe><h4><a href="https://leetcode.com/problems/subsets-ii/description/"><strong>90. Subsets II</strong></a></h4><p>Same problem with the added constraint that the set may contain duplicates but the output power set should not contain duplicate subsets.</p><p>Approach: Sort the given array beforehand and skip over duplicates while backtracking, essentially a simple 2 line change in the previous solution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0e23d712b21af2440e4cdc9ac37c844/href">https://medium.com/media/d0e23d712b21af2440e4cdc9ac37c844/href</a></iframe><h4><a href="https://leetcode.com/problems/combination-sum/description/"><strong>39. Combination Sum</strong></a></h4><p>Notice that we’ll have to explore many cases and there is no “smart” way to avoid that, the only smart thing we could do is to stop exploring a case as soon as we know it won’t lead to the solution and so this is a backtracking problem.</p><p>The solution is entirely same as subsets solution, only with a slight modification that we have a constraint included: the sum of the final collected combination should equal target.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fd7dd29650a240add1f6eb2d63f3ba7/href">https://medium.com/media/4fd7dd29650a240add1f6eb2d63f3ba7/href</a></iframe><h4><a href="https://leetcode.com/problems/combination-sum-ii/description/">40. Combination Sum II</a></h4><p>This problem bears the same relation to the previous problem as subsets-2 had with subsets, as such it should be no surprise that the same strategy works!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cd31870c23e60c446e9537d09f7b20b/href">https://medium.com/media/1cd31870c23e60c446e9537d09f7b20b/href</a></iframe><p>Honestly, visualizing the flow of the recursive function above is kinda trippy. Once you get comfortable writing this back and forth flow, backtracking problems are really easy. Also as I was writing this article I had an idea to make it simpler, so here is a simpler version of the subsets solution.(could be extended for other solutions in this post as well)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11130b915c9db4234622648d7b9d650a/href">https://medium.com/media/11130b915c9db4234622648d7b9d650a/href</a></iframe><p>Time for one final problem without which our discussion on backtracking would be considered incomplete, one of the classic computer science problems which gave birth to this paradigm.</p><h4><a href="https://leetcode.com/problems/n-queens/description/">51. N-Queens</a></h4><p>We try placing queens column by column. Place a queen, go to next column and try placing another queen such that it doesn’t face a queen in the same row or diagonals ( which is checked in validateSpot method ), and keep going. If we encounter an invalid spot we backtrack and keep trying other spots in that column vertically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28fd4a3578bb9c96824ef7ad11ae0d68/href">https://medium.com/media/28fd4a3578bb9c96824ef7ad11ae0d68/href</a></iframe><p>The validateSpot method can be made more efficient by using arrays to store the diagonals and rows already occupied. If you are interested, do check out this <a href="https://leetcode.com/problems/n-queens/discuss/19808/Accepted-4ms-c++-solution-use-backtracking-and-bitmask-easy-understand.">solution</a></p><p>Finally the point I mentioned earlier, when does a backtracking problem convert to a DP one? Let’s take an example:</p><ul><li>Return all ways to climb stairs, jumps allowed in steps 1 -&gt; k</li></ul><p><a href="https://codefights.com/interview-practice/task/cAXEnPyzknC5zgd7x">Technical Interview Coding Practice - CodeFights</a></p><ul><li>Count ways to climb stairs, jumps allowed in steps 1-&gt; k</li></ul><p><a href="https://www.geeksforgeeks.org/climb-n-th-stair-with-all-jumps-from-1-to-n-allowed-three-different-approaches/">Climb n-th stair with all jumps from 1 to n allowed (Three Different Approaches) - GeeksforGeeks</a></p><p>The first would require backtracking as we actually need all the ways, while the 2nd one could be done using DP optimally and is similar to how we optimize calculating Fibonacci numbers with memoization.</p><p>In the next post we’ll see solutions to these problems as well as explore other such cases (the standard rod cutting problem vs the subsets problem above). Understanding when to use DP is in itself a major issue. At this point I would like to point out the strong bond between recursion, backtracking, depth first search, and dynamic programming. (mega pattern if you will! )</p><p>The next few posts will be on solely focused on decoding DP patterns as many of you have requested the same. Stay tuned for upcoming posts!</p><p>References:</p><ul><li><a href="https://leetcode.com/problems/subsets/discuss/27281/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partitioning">discuss thread on backtracking</a></li><li><a href="https://stackoverflow.com/questions/1294720/whats-the-difference-between-backtracking-and-depth-first-search">backtracking vs dfs</a></li><li><a href="https://www.geeksforgeeks.org/backtracking-algorithms/">geeksforgeeks backtracking</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d9e5a03dc26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/leetcode-patterns/leetcode-pattern-3-backtracking-5d9e5a03dc26">Leetcode Pattern 3 | Backtracking</a> was originally published in <a href="https://medium.com/leetcode-patterns">Leetcode Patterns</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Pattern 2 | Sliding Windows for Strings]]></title>
            <link>https://medium.com/leetcode-patterns/leetcode-pattern-2-sliding-windows-for-strings-e19af105316b?source=rss----239b747456f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/e19af105316b</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[csgator]]></dc:creator>
            <pubDate>Wed, 10 Jan 2018 06:43:30 GMT</pubDate>
            <atom:updated>2021-11-18T02:47:18.707Z</atom:updated>
            <content:encoded><![CDATA[<p>A fellow redditor from <a href="https://www.reddit.com/r/cscareerquestions/">/r/cscareerquestions</a> pointed me to this awesome <a href="https://discuss.leetcode.com/topic/68976/sliding-window-algorithm-template-to-solve-all-the-leetcode-substring-search-problem">thread</a> on leetcode discuss which reveals the sliding window pattern for solving multiple string (substring) problems. Today we’ll explore the intuition behind this powerful technique and apply it to some very famous string problems. Another fact I aim to prove is that some problems tagged as hard are really easy once we grasp the required pattern.</p><p>I strongly believe in learning by doing, so let’s walk through a super simple example to understand how sliding windows work and then come back to leetcode problems. A sliding window approach generally helps us reduce the time complexity for brute force approaches.</p><pre>Given an array of integers of size <strong>‘n’</strong>.<br>Our aim is to calculate the maximum sum possible for <strong>‘k’</strong> consecutive elements in the array.<br><br>Input  : arr[] = {100, 200, 300, 400}<br>         k = 2<br>Output : 700</pre><p>To solve it using brute force means to explore all possible cases. We really don’t care about efficiency at this point but do want correct results. So we could run a nested loop exploring all windows of length k in the given array and pick the max sum.</p><pre>// BRUTE FORCE : iterate through all windows of size k</pre><pre>for(int i = 0; i &lt; n-k+1; i++){    <br>    int current_sum = 0;<br>     <br>    for(int j = 0; j &lt; k; j++){        <br>        current_sum = current_sum + arr[i+j];         <br>    }</pre><pre>    max_sum = max(current_sum, max_sum);    // pick maximum sum <br>}</pre><p>Now notice that having computed the sum of 1st window (size k), in order to get the sum of the next overlapping window we just need to leave out the leftmost item value and add the new (rightmost) item’s value, so we are essentially saving the re-computation of the sum for the non-changing part of the window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMCjDprUdgiQI-2kbroDqA.jpeg" /></figure><pre>int max_sum = 0, window_sum = 0; </pre><pre>/* calculate sum of 1st window */<br>for (int i = 0; i &lt; k; i++)  window_sum += arr[i]; </pre><pre>/* slide window from start to end in array. */<br> <br>for (int i = k; i &lt; n; i++){ <br>    window_sum += arr[i] - arr[i-k]; <strong>   </strong>// saving re-computation<br>    max_sum = max(max_sum, window_sum);<br>}</pre><p>Voila ! we used memory to save time, a very classic trade-off in algorithms and sliding windows are all about this as we’ll see. Time complexity reduced from O(n²) to O(n). Now let’s get to actual leetcode problems.</p><p><a href="https://leetcode.com/problems/minimum-window-substring/description/">76. Minimum Window Substring</a></p><p><em>note : this first problem has been brutally analyzed as this is a tricky concept and forms the basis to solve the next 5. Master this one and try the rest on your own, that would be the best way to learn.</em></p><p>In the previous example the window was of a fixed size, but here we use a window of variable size determined by <em>begin</em> and <em>end</em> markers. A brute force approach would be to iterate through all possible substrings and determine the minimum window which contains all characters of T. How do you see if a substring has all characters of T ? You could use the frequency table of T which stores character to number of occurrences as follows :</p><pre># initialize frequency table<br>for char c in T do <br>    table[c]++;<br>end</pre><pre>counter = table.size()                 # unique chars in T</pre><pre>for char c in string B do<br>    if(char c in table){ <br>        table[c]--;                    # decrement count for c<br>        if(table[c] == 0) counter--;<br>    }<br>end</pre><pre>if(counter == 0){ # B has every character in T }</pre><p>So we are basically assuring that every unique character in T exists in B as many times as it exists in T by maintaining a counter. It is fine if there are 4 ‘K’s in T and B has 7 ‘K’s , the table count for ‘K’ would simply go negative, but it goes to 0 at some point before that, proving string B has at least 4 &#39;K’s in it, satisfying the need with respect to “K”, extending the logic to other chars in T if counter = 0, B has all chars in T.</p><p>Okay so coming to the sliding window part here, we keep sliding <em>end</em> to the right examining each new character and updating the count in table. As soon as we hit counter = 0, it means we have a valid answer so we try to trim it down removing the unessential characters from the start by sliding begin right. We constantly keep trying to validate / invalidate the string by manipulating counter and table counts.</p><p>Take a moment, understand this code. Walk through it on paper for this example : [ S : ADOBECODEBANC | T :&quot;ABC&quot; ] . Do not worry, the code is just heavily annotated, it is actually very concise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff18843e6c3968c3d288b2473cbba15e/href">https://medium.com/media/ff18843e6c3968c3d288b2473cbba15e/href</a></iframe><p>Intuition : the best substring for the answer would simply be a permutation of T if such a substring exists in S, but otherwise we could have wasteful characters sitting in between the essential characters that make the substring valid as an answer. Our attempt here is to remove such chars without losing the necessary ones. After trimming down as much as possible we resume with sliding <em>end</em> right and repeating the whole process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73BE2cg_UyNgk6LI9J7wsQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqonc_hghOjQd8P7m9IFOg.jpeg" /></figure><p>Whenever counter = 0 we have a valid candidate for our ans, but we update ans only if it is shorter than previously recorded minimum length ans.</p><h4><a href="https://leetcode.com/problems/find-all-anagrams-in-a-string/description/">438. Find All Anagrams in a String</a></h4><p>Exactly the same as above with the added condition that the substring should be of length equal to p and that we have to return indexes of all such occurrences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7614ae6ce266aca07e98fabe54b34c1/href">https://medium.com/media/f7614ae6ce266aca07e98fabe54b34c1/href</a></iframe><h4><a href="https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/">30. Substring with Concatenation of All Words</a></h4><p>Here comes my proof that not all Leetcode “hard” are exactly hard, this one is simply a slight modification of the above problem which is tagged “easy”. Instead of chars in above question now we have words so it got a bit messier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad31a91199081b4a643c752263c750a7/href">https://medium.com/media/ad31a91199081b4a643c752263c750a7/href</a></iframe><h4><a href="https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/">3. Longest Substring Without Repeating Characters</a></h4><p>Here we build the frequency table out of the substring we explored so far as the aim is to find longest susbstring without any repetitions. So similar to above case we slide <em>end</em> and keep building the table and as soon as we hit a repetition, meaning the <em>end char</em> is already in table, we start sliding <em>begin</em>. We record the max before sliding <em>begin</em> for the ans.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/329117d9f6793383e2ab7244a52eb556/href">https://medium.com/media/329117d9f6793383e2ab7244a52eb556/href</a></iframe><h4><a href="https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/submissions/1">159. Longest Substring with At Most Two Distinct Characters</a></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f03f9e24012cef7bcb16f2c5c175046b/href">https://medium.com/media/f03f9e24012cef7bcb16f2c5c175046b/href</a></iframe><h4><a href="https://leetcode.com/problems/permutation-in-string/description/">567. Permutation in String</a></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81b31c2deec4339874a15a9b078072de/href">https://medium.com/media/81b31c2deec4339874a15a9b078072de/href</a></iframe><p>Other problems that can be solved similarly:</p><p><a href="https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/submissions/1"><strong>340. Longest Substring with At Most K Distinct Characters</strong></a><strong> </strong>which is literally the same as the one with K = 2.</p><p><a href="https://leetcode.com/problems/longest-repeating-character-replacement/description/"><strong>424. Longest Repeating Character Replacement</strong></a></p><p>A good exercise at this point would be to think why the sliding window approach actually works, draw out all the cases possible for the minimum window substring problem and you’ll have a deeper intuition into this technique.</p><p>Some interesting facts :</p><ol><li>It took me less time to actually solve these problems than what it took me to figure out how to explain it in writing.</li><li>I solved a problem tagged hard first and the corresponding easy problem later as I use an extension to hide the difficulty levels on leetcode loll.</li><li>I strongly believe understanding how a programmer wrote code is more important than the code itself and so I am working on <a href="https://github.com/sourabh2k15/codeback">codeback</a> , a code playback tool allowing users to stop, edit and play the code line by line as well as execute the code to see output.</li></ol><p>Stay tuned and feel free to connect with me on LI : <a href="https://www.linkedin.com/in/csgator/">https://www.linkedin.com/in/csgator/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19af105316b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/leetcode-patterns/leetcode-pattern-2-sliding-windows-for-strings-e19af105316b">Leetcode Pattern 2 | Sliding Windows for Strings</a> was originally published in <a href="https://medium.com/leetcode-patterns">Leetcode Patterns</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Pattern 1 | DFS + BFS == 25% of the problems — part 2]]></title>
            <link>https://medium.com/leetcode-patterns/leetcode-pattern-2-dfs-bfs-25-of-the-problems-part-2-a5b269597f52?source=rss----239b747456f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/a5b269597f52</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[csgator]]></dc:creator>
            <pubDate>Tue, 09 Jan 2018 23:25:04 GMT</pubDate>
            <atom:updated>2018-01-06T23:24:46.633Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leetcode Pattern 1 | DFS + BFS == 25% of the problems — part 2</h4><p>Hola again ! Thanks for all the positive feedback. It really motivates me to keep writing daily. Many people actually asked me to write on DP patterns next as that is the most dreaded topic in interview prep. I would dedicate the next few posts to the same, building intuition on some non-trivial DP problems but for today let’s complete BFS. Some useful tips for DP to help you out till then:</p><ol><li>Solve 3 DP problems each day for 2 weeks and you’ll start getting a hang of the underlying patterns. Struggle a bit, think hard, lookup the solution after an hour or two, <strong>understand the intuition deeply</strong>, repeat.</li><li>Think hard on the classic DP problems ( which are only a handful ), discuss / explain the intuition to a peer, draw it out on paper ( very important ) and you would then be able to solve most DP problems.</li><li>Read solutions to DP problems from <a href="https://www.geeksforgeeks.org/dynamic-programming/">geeksforgeeks</a> or watch <a href="https://www.youtube.com/watch?v=8LusJS5-AGo&amp;list=PLrmLmBdmIlpsHaNTPP_jHHDx_os9ItYXr&amp;index=1">Tushar Roy</a>’s playlist on DP, the whole point is to accustom yourself with solutions to standard problems and then apply that intuition elsewhere.</li></ol><p>Honestly DP is overrated, it is totally doable. Just break out of the ‘DP is wicked hard’ phase and start solving problems. Over the next few days I am going to follow the above outlined techniques and share some insights every day.</p><p><strong>BFS:</strong></p><p>Again let’s start with a tree, cause we are so obsessed with trees! level order traversal is simply a BFS and a rather simple one at that !</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31eac6622e108439b9801b067378cd29/href">https://medium.com/media/31eac6622e108439b9801b067378cd29/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWbRC11sobOP2YDlgPOxug.jpeg" /></figure><h4><a href="https://leetcode.com/problems/binary-tree-level-order-traversal/">102. Binary Tree Level Order Traversal</a></h4><p>The leetcode problem on level order traversal is a bit more involved than the above mentioned simple traversal. They require you to store each level result in an array and return final result as array of arrays. Just imagine somebody told you to put a line break after printing each level, that would essentially be the same problem.</p><p><strong>1st approach</strong></p><p>Using the above simple code it is not possible to know when a new level starts. I originally solved this problem using 2 queues, but I found this amazing approach in discuss and I have adopted it since then. (discuss is where the true learning happens ;) ). We use a dummy node as marker to mark level ends. Try visualizing the horizontal queue push- pop action going on in BFS and figure out how you could use an extra dummy node to mark level ends, then go through below code. This approach simply blew my mind !</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4460052a941e666a1ab5bfcd4fd749b8/href">https://medium.com/media/4460052a941e666a1ab5bfcd4fd749b8/href</a></iframe><p>EDIT: As <a href="https://www.linkedin.com/in/khanshad/">Shad Khan</a> suggested on LI, we could eliminate the dummy node using the size of queue to keep track of level. Here is his Python code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*sBKdlza0AaZhoC_BpO6N1g.png" /></figure><p><strong>2nd approach</strong></p><p>Let’s play a <strong>game of 2 queues</strong>. We keep 2 queues for even and odd levels of the tree. So starting with 0th level i.e root, <strong>initialize even queue with root</strong>. Now imagine holding the even queue in your right hand and the odd queue in your left ( just 2 boxes which allow entry from only one side and exit from the opposite side).</p><ol><li>Tilt your right hand so all the contents of even queue start falling out. <strong>Whenever a node falls out of a queue push it’s children into the other queue.</strong></li><li>Now tilt your left hand emptying contents of odd queue and adding kids of falling out nodes into even queue.</li><li>Repeat until both queues are empty.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdb0a8024f455961e39e2b8686e6d2c9/href">https://medium.com/media/bdb0a8024f455961e39e2b8686e6d2c9/href</a></iframe><p><a href="https://leetcode.com/problems/symmetric-tree/"><strong>101. Symmetric Tree</strong></a> problem also can be solved using 2 queue method in a slightly different way, but enough with trees already! Let’s see an actual graph (matrix) problem using BFS.</p><h4><a href="https://leetcode.com/problems/01-matrix/">542. 01 Matrix</a></h4><p>How does one know that we need BFS here and not DFS, which is a very true dilemma is many problems, well the first thought that crosses my mind seeing this problem is if somehow I could iterate through all 0&#39;s in matrix and start a recursive action at these cells updating distances of neighboring cells by 1, keep doing so and stop only if the cell under consideration is already closer to another 0.</p><p>For this to be successful we need all those actions to execute only 1 round at a time ( visit 4 neighbors ) and then <strong>wait for all others</strong> to execute their 1 rounds so recursion doesn’t work ( DFS failed only 1 option left BFS). See how this is so similar to the tree case when we needed the kids of the current node <strong>only after</strong> we have visited nodes at same level, it’s a BFS , bingo! The reason we need this here is if we don’t wait for other actions to execute a round how would we know if the current cell is already closer to another 0 in which case we need to stop BFS operation for that cell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baae18aa9adaf50e9c5d4a46003b412a/href">https://medium.com/media/baae18aa9adaf50e9c5d4a46003b412a/href</a></iframe><p><strong>Concluding thoughts on BFS</strong> :</p><ol><li>Problems in which you have to find shortest path are most likely calling for a BFS.</li><li>For graphs having unit edge distances, shortest paths from any point is just a BFS starting at that point, no need for Dijkstra’s algorithm.</li><li>Maze solving problems are mostly shortest path problems and every maze is just a fancy graph so you get the flow.</li></ol><p>Enjoy and stay tuned !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b269597f52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/leetcode-patterns/leetcode-pattern-2-dfs-bfs-25-of-the-problems-part-2-a5b269597f52">Leetcode Pattern 1 | DFS + BFS == 25% of the problems — part 2</a> was originally published in <a href="https://medium.com/leetcode-patterns">Leetcode Patterns</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Pattern 1 | BFS + DFS == 25% of the problems — part 1]]></title>
            <link>https://medium.com/leetcode-patterns/leetcode-pattern-1-bfs-dfs-25-of-the-problems-part-1-519450a84353?source=rss----239b747456f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/519450a84353</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[whiteboarding]]></category>
            <dc:creator><![CDATA[csgator]]></dc:creator>
            <pubDate>Tue, 09 Jan 2018 23:24:47 GMT</pubDate>
            <atom:updated>2018-01-11T22:46:20.695Z</atom:updated>
            <content:encoded><![CDATA[<p>It is amazing how many graph, tree and string problems simply boil down to a DFS (Depth-first search) / BFS (Breadth-first search). Today we are going to explore this basic pattern in a novel way and apply the intuition gained to solve some medium problems on Leetcode.</p><p>Let us build on top of <a href="https://medium.com/@sourabreddy/leetcode-pattern-0-iterative-traversals-on-trees-d373568eb0ec">pattern 0</a>. First of, a tree can be thought of as a connected acyclic graph with N nodes and N-1 edges. Any two vertices are connected by <em>exactly one</em> path. So naturally the question arises, what about a DFS or a BFS on binary trees ? well there are 6 possible DFS traversals for binary trees ( 3 rose to fame while the other 3 are just symmetric )</p><ol><li>left, right, root ( Postorder) ~ 4. right, left, root</li><li>left, root, right ( Inorder) ~ 5. right, root, left</li><li>root, left, right ( Preorder) ~ 6. root, right, left</li></ol><p>And there is one BFS which is the level order traversal ( can be done using queue). Let us analyze the DFS pattern using a stack which we are already familiar with.</p><p>DFS is all about diving as deep as possible before coming back to take a dive again. Below is the iterative DFS pattern using a stack that will allow us to solve a ton of problems. ( iterative introduced first so as to develop intuition)</p><blockquote>DFS magic spell: 1]push to stack, 2] pop top , 3] retrieve unvisited neighbours of top, push them to stack 4] repeat 1,2,3 while stack not empty. Now form a rap !</blockquote><h4><a href="https://leetcode.com/problems/binary-tree-preorder-traversal/">144. Preorder Traversal</a></h4><p>Let’s walk through the above spell using an example tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRAluXfuPRVLjLDOgf6NPQ.jpeg" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dd9e9a85ddd5c6265459cf36c35eb61/href">https://medium.com/media/6dd9e9a85ddd5c6265459cf36c35eb61/href</a></iframe><p>Two things to ponder on as we move further:</p><p>1] Why are we using stack for DFS , couldn’t we use a queue ? ( always remember : stack for DFS, imagine a vertical flow | queue for BFS, horizontal flow, more on this later)</p><p>2] How do we extend this DFS process to general graphs or graphs disguised as matrices ( as in most LC problems). ( Include a mechanism to track visited)</p><h4><a href="https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/">323. Number of Connected Components in an Undirected Graph</a></h4><p>The base problem upon which we will build other solutions is this one which directly states to find the number of connected components in the given graph. We could use DFS / BFS to solve this. Below is the DFS code using the stack spell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dc05f0e6a20b50b745c61f4ceb45086/href">https://medium.com/media/4dc05f0e6a20b50b745c61f4ceb45086/href</a></iframe><h4><a href="https://leetcode.com/problems/number-of-islands/">200. Number of Islands</a></h4><p>This falls under a general category of problems where in we just need to find the number of connected components but the details could be twisted.</p><p>The intuition here is that once we find a “1” we could initiate a new group, if we do a DFS from that cell in all 4 directions we can reach all 1’s connected to that cell and thus belonging to same group. We could mark these as visited and move on to count other groups. One optimization here is that we don’t need the matrix later so we could as well destroy the visited cells by placing a special character saving us extra memory for the visited array.</p><p>Even if we needed the matrix later one could always restore the original value after the dfs call. Below is a simple recursive DFS solution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9995a54532492cb45e5fa5affae63a6c/href">https://medium.com/media/9995a54532492cb45e5fa5affae63a6c/href</a></iframe><h4><a href="https://leetcode.com/problems/friend-circles/description/">547. Friend Circles</a></h4><p>Same concept, find connected components. The only twist is that the connected neighbors are presented in a different form. Here we don’t destroy the matrix, but use an array to keep track of visited ( friendZoned ). Notice the stack pattern, it is exactly the same as in connected components problem. All that changes is the way neighbors are defined. If we were to write an iterative version for the islands problems, it would also be very similar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/947c75b3d1104686ec87e25937504ea9/href">https://medium.com/media/947c75b3d1104686ec87e25937504ea9/href</a></iframe><p>I broke this post into 2 parts as it got too long, I will visit BFS in the next part. So let’s conclude this part by pondering on why we always use stack for dfs and queue for bfs. Have you ever wondered why we don’t use queue for dfs or stack for bfs? questions like these really give us some insights on the difference between stacks and queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evWtdhUMmRDU1blercHv4g.jpeg" /></figure><p>So using a stack I could pop 2 and push it’s kids and keep doing so eventually exhausting 2’s subtrees, 3 stays calmly in the stack just below the part where the real push-pop action is going, we pop 3 when all subtrees of 2 are done. This feature of stack is essential for DFS.</p><p>While in a queue, I could dequeue 2 and enqueue it’s subtrees which go behind 3 as it was already sitting in the queue. So the next time I dequeue I get 3 and only after that do I move on to visiting 2’s subtrees, this is essentially a BFS !</p><p>For me this revelation was pure bliss. Take a moment to celebrate the history of Computer Science and the geniuses behind these simple yet powerful ideas.</p><p><a href="http://people.idsia.ch/~juergen/bauer.html">http://people.idsia.ch/~juergen/bauer.html</a></p><p>Do comment your views and feel free to connect with me on LI : <a href="https://www.linkedin.com/in/sourabh-reddy">https://www.linkedin.com/in/sourabh-reddy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=519450a84353" width="1" height="1" alt=""><hr><p><a href="https://medium.com/leetcode-patterns/leetcode-pattern-1-bfs-dfs-25-of-the-problems-part-1-519450a84353">Leetcode Pattern 1 | BFS + DFS == 25% of the problems — part 1</a> was originally published in <a href="https://medium.com/leetcode-patterns">Leetcode Patterns</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Pattern 0 | Iterative traversals on Trees]]></title>
            <link>https://medium.com/leetcode-patterns/leetcode-pattern-0-iterative-traversals-on-trees-d373568eb0ec?source=rss----239b747456f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/d373568eb0ec</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[whiteboarding]]></category>
            <dc:creator><![CDATA[csgator]]></dc:creator>
            <pubDate>Tue, 09 Jan 2018 23:24:28 GMT</pubDate>
            <atom:updated>2018-03-01T19:40:31.544Z</atom:updated>
            <content:encoded><![CDATA[<p>The key to solve algorithm problems posed in technical interviews or elsewhere is to quickly identify the underlying patterns. This is my attempt to decompose <a href="https://leetcode.com/">leetcode</a> problems and group them into minimal sets. I figured out this would be a useful insight for future people in tech ( long live whiteboards !) to actually write a series of short blog posts.</p><p>Here I present one such powerful pattern related to trees and present 3 different problems that can be solved using this pattern. Whenever you solve a tree problem using recursion, always follow it up writing an iterative solution and vice-versa.</p><p>Iterative solutions help us really understand what is going on while recursion is concise and beautiful, we need to be able to write both in order to become good programmers.</p><p>An iterative in-order traversal using stack to solve multiple tree problems:</p><h4><a href="https://leetcode.com/problems/binary-tree-inorder-traversal/description/">Inorder Traversal of Binary Tree</a></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8cd2bf02d13115d305205298dc12832/href">https://medium.com/media/b8cd2bf02d13115d305205298dc12832/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qRceG8aZR8KBCUP2svSBw.jpeg" /></figure><h4><a href="https://leetcode.com/problems/validate-binary-search-tree/">Validate if Tree is a BST</a></h4><p>For a binary tree to be a BST, the inorder has to be in sorted (ascending) order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6281d7bf3c824f238305af86460131e/href">https://medium.com/media/c6281d7bf3c824f238305af86460131e/href</a></iframe><h4><a href="https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/">Kth Smallest element in BST</a></h4><p>Inorder traversal of a BST gives us a sorted order of the items in it. So a simple inorder breaking off at the kth item would give us our answer !</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e3eb234775e7d850a624ac489e4cb81/href">https://medium.com/media/3e3eb234775e7d850a624ac489e4cb81/href</a></iframe><p>Try doing this for preorder and postorder too and see how many new problems you would have unlocked ! ( Share your solutions in the comments )</p><p>I am also going to translate the solutions into Java and Python as I progress, feel free to contribute back by sharing your own patterns or translating code into your favorite language of choice.</p><p>Also feel free to connect with me on LI : <a href="https://www.linkedin.com/in/sourabh-reddy/">https://www.linkedin.com/in/sourabh-reddy/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d373568eb0ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/leetcode-patterns/leetcode-pattern-0-iterative-traversals-on-trees-d373568eb0ec">Leetcode Pattern 0 | Iterative traversals on Trees</a> was originally published in <a href="https://medium.com/leetcode-patterns">Leetcode Patterns</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>