<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Anurag Goel</title>
    <description>The latest articles on DEV Community by Anurag Goel (@algosimplified).</description>
    <link>https://dev.to/algosimplified</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4280191%2Fce6457b5-94cf-4b8a-aea3-39afa91fd717.png</url>
      <title>DEV Community: Anurag Goel</title>
      <link>https://dev.to/algosimplified</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/algosimplified"/>
    <language>en</language>
    <item>
      <title>How to Read India's Market Mood Index Without Treating It as a Signal</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 10:11:54 +0000</pubDate>
      <link>https://dev.to/algosimplified/how-to-read-indias-market-mood-index-without-treating-it-as-a-signal-8h6</link>
      <guid>https://dev.to/algosimplified/how-to-read-indias-market-mood-index-without-treating-it-as-a-signal-8h6</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://www.multibaggerlab.com/blog-market-mood-index" rel="noopener noreferrer"&gt;MultibaggerLab&lt;/a&gt;. That URL is canonical. The full guide has the source list, a longer FAQ and a same-day breakdown of the 20 November 2026 signals. This is a shorter, restructured cut of the same explainer.&lt;/p&gt;

&lt;p&gt;The Market Mood Index (MMI) is a 0 to 100 score that tries to show whether Indian investors are fearful or greedy right now. Tickertape builds it from six market signals. Below 30 is extreme fear, above 70 is extreme greed. The best use of that number is as a check on the crowd's emotions, and on your own. It is not a buy or sell button.&lt;/p&gt;

&lt;p&gt;One reason the distinction matters showed up in late 2026. India VIX was higher on 20 November (17.32) than at the September low in mood (13.49), even though MMI had swung from extreme fear to extreme greed. Volatility alone is a poor mood gauge. MMI mixes in five other signals, and even then the single number can hide disagreement underneath.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the index is, and what it is not
&lt;/h2&gt;

&lt;p&gt;Markets swing between two emotions. When prices rise for a while, people get greedy and chase. When prices fall, they panic and sell. MMI tries to put a number on that mood.&lt;/p&gt;

&lt;p&gt;Tickertape, an Indian investing platform, publishes it on a scale of 0 to 100. It works much like CNN's Fear &amp;amp; Greed Index for the US market, but with Indian inputs, and it updates during market hours. It is a private tool. It is not an official NSE or SEBI index.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;MMI reading&lt;/th&gt;
&lt;th&gt;Zone&lt;/th&gt;
&lt;th&gt;What it suggests&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Below 30&lt;/td&gt;
&lt;td&gt;Extreme fear&lt;/td&gt;
&lt;td&gt;Heavy pessimism; the market may be oversold&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;30 to 50&lt;/td&gt;
&lt;td&gt;Fear&lt;/td&gt;
&lt;td&gt;Cautious, risk-averse mood&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;50 to 70&lt;/td&gt;
&lt;td&gt;Greed&lt;/td&gt;
&lt;td&gt;Investors willing to take more risk&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Above 70&lt;/td&gt;
&lt;td&gt;Extreme greed&lt;/td&gt;
&lt;td&gt;Crowded optimism; the market may be overbought&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The limits for extreme fear and extreme greed come from Tickertape. The 30 to 50 and 50 to 70 bands are as described by DBS Bank India.&lt;/p&gt;

&lt;h2&gt;
  
  
  The six inputs, in plain words
&lt;/h2&gt;

&lt;p&gt;Tickertape says the index gives equal weight to six inputs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;FII activity: FIIs' net open positions in NSE index futures. Points to greed when FIIs hold more longs than usual.&lt;/li&gt;
&lt;li&gt;Volatility and skew: India VIX, plus the gap between put and call option pricing. Points to greed when VIX and put demand are below normal.&lt;/li&gt;
&lt;li&gt;Momentum: the gap between the Nifty's 90-day and 30-day moving averages. Points to greed when the short-term trend is above the longer one.&lt;/li&gt;
&lt;li&gt;Market breadth: advancing versus declining stocks, adjusted for volume. Points to greed when rising stocks carry most of the volume.&lt;/li&gt;
&lt;li&gt;Price strength: stocks near 52-week highs minus stocks near 52-week lows. Points to greed when many more stocks sit near highs.&lt;/li&gt;
&lt;li&gt;Demand for gold: gold's return versus the Nifty over two weeks. Points to greed when gold lags equities.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Two jargon terms, once. Open interest is the number of futures or options contracts still outstanding at the end of the day. Skew is how much more traders pay for protection against a fall (puts) than for a bet on a rise (calls).&lt;/p&gt;

&lt;p&gt;One honest caveat. Tickertape does not publish how it scales each input into the final score. Its own FAQ also calls VIX "1 of 7 components", probably because it counts volatility and skew separately. You can understand the ingredients. You cannot rebuild the exact number at home.&lt;/p&gt;

&lt;h2&gt;
  
  
  What 2026 looked like, month by month
&lt;/h2&gt;

&lt;p&gt;The stretch from July to November 2026 is a useful test, because the market went through a real fall and a real recovery. Month-end MMI readings from Tickertape were matched with NSE's official close data for the same days.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Date (2026)&lt;/th&gt;
&lt;th&gt;MMI&lt;/th&gt;
&lt;th&gt;Zone&lt;/th&gt;
&lt;th&gt;Nifty 50 close&lt;/th&gt;
&lt;th&gt;Nifty PE&lt;/th&gt;
&lt;th&gt;India VIX&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;31 Jul&lt;/td&gt;
&lt;td&gt;73.0&lt;/td&gt;
&lt;td&gt;Extreme greed&lt;/td&gt;
&lt;td&gt;24,383.60&lt;/td&gt;
&lt;td&gt;20.78&lt;/td&gt;
&lt;td&gt;11.76&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;31 Aug&lt;/td&gt;
&lt;td&gt;47.6&lt;/td&gt;
&lt;td&gt;Fear&lt;/td&gt;
&lt;td&gt;24,080.40&lt;/td&gt;
&lt;td&gt;20.36&lt;/td&gt;
&lt;td&gt;11.19&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;30 Sep&lt;/td&gt;
&lt;td&gt;19.2&lt;/td&gt;
&lt;td&gt;Extreme fear&lt;/td&gt;
&lt;td&gt;22,620.45&lt;/td&gt;
&lt;td&gt;19.36&lt;/td&gt;
&lt;td&gt;13.49&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;30 Oct&lt;/td&gt;
&lt;td&gt;50.4&lt;/td&gt;
&lt;td&gt;Greed&lt;/td&gt;
&lt;td&gt;23,053.10&lt;/td&gt;
&lt;td&gt;19.30&lt;/td&gt;
&lt;td&gt;15.30&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;20 Nov&lt;/td&gt;
&lt;td&gt;74.8&lt;/td&gt;
&lt;td&gt;Extreme greed&lt;/td&gt;
&lt;td&gt;25,800.60&lt;/td&gt;
&lt;td&gt;21.02&lt;/td&gt;
&lt;td&gt;17.32&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;MMI sat in extreme greed at the end of July, and the Nifty fell about 7.2% over the next two months. It hit extreme fear near 19 at the end of September, and the Nifty then rose about 14% to 20 November.&lt;/p&gt;

&lt;p&gt;Look at the VIX column too. Volatility was higher in November's greed than in September's fear. That is the limit of using VIX on its own.&lt;/p&gt;

&lt;p&gt;A hindsight, price-only example. â‚¹1 lakh put into the Nifty 50 at the 31 July close, when MMI read 73, would have been worth about â‚¹1,05,800 by 20 November. The same â‚¹1 lakh put in on 30 September, when MMI read 19, would have been about â‚¹1,14,100. That is a â‚¹8,300 gap from timing alone. This is one stretch of four months, picked after the fact. It ignores costs, taxes and dividends, and it does not prove the pattern repeats.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why the headline number can still mislead you
&lt;/h2&gt;

&lt;p&gt;On Friday 20 November MMI closed at 74.8, in extreme greed. On Monday 23 November at about 10:18 IST it read 70.3, right at the edge of that zone. The Nifty had closed Friday at 25,800.60, up 1.1% on the day.&lt;/p&gt;

&lt;p&gt;The underlying signals did not all agree. FIIs were net buyers of â‚¹10,308 crore in the cash market that day (provisional, NSE data via Tapetide), but in index futures they held 75,864 long contracts against 1,46,318 short ones, only 34% long (NSE participant-wise open interest). India VIX was 17.32, up 7.5% on the day. In the US, the Nasdaq was down 5.3% and the CBOE VIX was 35.9.&lt;/p&gt;

&lt;p&gt;So the greed reading was real, but it rested on a narrower base than the headline suggests. Nervousness was rising even as prices went up.&lt;/p&gt;

&lt;h2&gt;
  
  
  Accuracy, limits, and a calmer way to use it
&lt;/h2&gt;

&lt;p&gt;Tickertape says its testing shows MMI is 91.28% accurate at flagging tops and bottoms. It does not publish how that test was run, what counts as a hit, or over which years. Treat the figure as a marketing claim until you can check it.&lt;/p&gt;

&lt;p&gt;Three bigger limits matter more than that number. Extremes can last: a market in extreme greed can stay there for weeks while prices keep rising. The index is backward-looking, because every input is built from prices and positions that already happened. And it ignores the price paid. MMI does not know whether the Nifty trades at 15 times earnings or 30. Valuation still matters more over five years.&lt;/p&gt;

&lt;p&gt;Think of it as a mirror, not a map. Its best use is to catch your own behaviour. Most of us feel brave after a rally and scared after a fall, which is the wrong way round. A simple way to use it, if you already have a long-term plan:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A regular SIP does not need a mood check.&lt;/li&gt;
&lt;li&gt;In extreme greed, a lump sum can be spread over a few months rather than put in on one day.&lt;/li&gt;
&lt;li&gt;In extreme fear, look at valuation and balance sheets before adding, not after the news calms down.&lt;/li&gt;
&lt;li&gt;Do not use MMI alone to sell a good business you planned to hold for years.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For valuation, the free official number is the &lt;a href="https://www.multibaggerlab.com/blog-nifty-pe-ratio" rel="noopener noreferrer"&gt;Nifty PE ratio&lt;/a&gt; from NSE. Note the zone and the direction: a move from 80 down to 70 means something different from 60 up to 70. Greed at a PE of 21 is not the same as greed at 26.&lt;/p&gt;

&lt;p&gt;CNN's Fear &amp;amp; Greed Index is the same idea for a different market. It uses seven US inputs, including the S&amp;amp;P 500 against its 125-day average, the put/call ratio, junk bond demand and stocks versus bonds. MMI swaps those for Indian signals such as FII futures positions and gold versus the Nifty. The two can disagree, as they did on 20 November 2026.&lt;/p&gt;

&lt;p&gt;The full write-up, with sources and a longer FAQ, is in the &lt;a href="https://www.multibaggerlab.com/blog-market-mood-index" rel="noopener noreferrer"&gt;canonical MultibaggerLab guide to the Market Mood Index&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;MultibaggerLab is not a SEBI-registered Investment Adviser or Research Analyst. Nothing here is investment advice or a stock recommendation. This is educational content only. Always do your own research.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>investing</category>
      <category>finance</category>
      <category>stocks</category>
      <category>india</category>
    </item>
    <item>
      <title>A 52-Week Low Is a Reason to Look, Not a Reason to Buy</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 10:06:46 +0000</pubDate>
      <link>https://dev.to/algosimplified/a-52-week-low-is-a-reason-to-look-not-a-reason-to-buy-clj</link>
      <guid>https://dev.to/algosimplified/a-52-week-low-is-a-reason-to-look-not-a-reason-to-buy-clj</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://www.multibaggerlab.com/blog-stocks-at-52-week-low" rel="noopener noreferrer"&gt;MultibaggerLab&lt;/a&gt;. That URL is canonical. The full guide has a longer filter-by-filter table, a fuller checklist and the 52-week-high comparison. This is a shorter, restructured cut of the same explainer.&lt;/p&gt;

&lt;p&gt;A stock at its lowest price in a year looks like a bargain. Sometimes it is. Often it is a business that is quietly getting worse. The low itself only tells you that the price has fallen. It says nothing about whether the business is still sound. The useful question is not "is it cheap?" It is: is the business still as good as it was when the stock was higher?&lt;/p&gt;

&lt;h2&gt;
  
  
  What a 52-week low is, and what it is not
&lt;/h2&gt;

&lt;p&gt;The 52-week low is the lowest price a stock has traded at over the last 52 weeks, roughly one trading year. A stock "hits a 52-week low" when today's price falls below that level. Most screeners also count a stock as "near" its low if it trades within 5 to 10% of it.&lt;/p&gt;

&lt;p&gt;NSE publishes the official daily list on its 52-week high/low page. Use that page, not a forwarded message-group list, as the starting point for live data.&lt;/p&gt;

&lt;p&gt;Lows can pile up even on a good day for the index. On 16 November 2026 the Nifty 50 closed up 0.58% at 25,291.10, yet NSE data showed 125 stocks at fresh 52-week lows against 109 at fresh highs, and 2,504 declining stocks against 1,168 advancing. The headline index can hide a lot of stocks that are still falling.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two kinds of fall
&lt;/h2&gt;

&lt;p&gt;A stock does not reach its lowest price in a year without a reason. The reason is what decides whether the low is worth studying.&lt;/p&gt;

&lt;p&gt;Temporary falls, which can turn out to be an opportunity, include a market-wide or sector-wide sell-off that hits good and bad companies alike; one weak quarter caused by a one-off cost, a delayed order or a raw-material spike; selling by large funds for their own reasons, such as index changes, redemptions or FII outflows; a stock that was simply too expensive a year ago and has come back to a more normal PE; or short-term worry over a policy change that does not hit long-term earnings much.&lt;/p&gt;

&lt;p&gt;Structural falls, which are often value traps, look different: earnings falling for several quarters in a row with no clear end; debt rising faster than profits, or interest eating into operating profit; promoters pledging more shares or selling their stake; a lost licence, a disruptive competitor, or a product going out of use; auditor resignations, delayed results, or governance questions.&lt;/p&gt;

&lt;p&gt;The first group is a cheaper price for the same business. The second is a worse business, and the lower price may be fair, or not low enough yet.&lt;/p&gt;

&lt;h2&gt;
  
  
  The value-trap test, plus the maths of a deep fall
&lt;/h2&gt;

&lt;p&gt;A value trap is a stock that looks cheap but stays cheap or keeps falling, because the business behind it is shrinking. The most common way people fall in is the PE ratio. When profits drop, the "E" in PE drops too, so a stock can look cheap on PE even as the business gets weaker.&lt;/p&gt;

&lt;p&gt;If the business is still intact, the fall is about price and sentiment. If it is not, the fall is the market telling you something.&lt;/p&gt;

&lt;p&gt;Also remember the maths of losses. A stock that falls 40% needs to rise about 67% just to get back to where it was, because 0.6 Ã— 1.67 is about 1. Buying a falling stock too early can mean sitting through that second leg down.&lt;/p&gt;

&lt;h2&gt;
  
  
  A quality screen, then a worked comparison
&lt;/h2&gt;

&lt;p&gt;The screen has two jobs: build a list of stocks near their low, then throw out the ones whose business has broken. A starting set of filters, in a Screener.in-style query, is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Current price within 10% of the 52-week low (widen to 15% if the list is too short)&lt;/li&gt;
&lt;li&gt;Market capitalisation above â‚¹1,000 crore, to reduce thinly traded names&lt;/li&gt;
&lt;li&gt;Return on capital employed above 15%, so the business still earns well on the money put into it&lt;/li&gt;
&lt;li&gt;Debt to equity below 0.5, so a bad year is survivable&lt;/li&gt;
&lt;li&gt;Promoter pledge below 5%, because falling prices can trigger forced selling of pledged shares&lt;/li&gt;
&lt;li&gt;Three-year profit growth and sales growth above 0, as a rough check that the long-term trend has not broken. Then read the last four to six quarters yourself.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These cut-offs are starting points, not rules. Banks and NBFCs need different measures, because debt to equity means little for a lender. Cyclical sectors such as metals can show high ROCE right at a peak.&lt;/p&gt;

&lt;p&gt;A hypothetical comparison, using made-up numbers, shows why price alone is not enough. Two companies, A and B, each have a 52-week high of â‚¹500 and a 52-week low of â‚¹300, and both now trade at â‚¹312. Each is 4% above its low (312 Ã· 300 = 1.04) and 37.6% below its high. On price they look the same.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Check&lt;/th&gt;
&lt;th&gt;Company A (example)&lt;/th&gt;
&lt;th&gt;Company B (example)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Why it fell&lt;/td&gt;
&lt;td&gt;Whole sector sold off; one weak quarter from a one-off cost&lt;/td&gt;
&lt;td&gt;Profits down for four quarters running&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ROCE&lt;/td&gt;
&lt;td&gt;21% (was 23%)&lt;/td&gt;
&lt;td&gt;8% (was 16%)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Debt to equity&lt;/td&gt;
&lt;td&gt;0.2, steady&lt;/td&gt;
&lt;td&gt;1.3, up from 0.6&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Promoter pledge&lt;/td&gt;
&lt;td&gt;0%&lt;/td&gt;
&lt;td&gt;30%, rising&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;PE&lt;/td&gt;
&lt;td&gt;18 (was 29)&lt;/td&gt;
&lt;td&gt;9, looks cheap only because profit fell&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Read&lt;/td&gt;
&lt;td&gt;Worth deeper research&lt;/td&gt;
&lt;td&gt;Likely value trap&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Company A is the same business at a lower price. Company B is a weaker business, and its low PE is a result of falling profit, not a bargain. Even for A, the next step is research: the annual report, management commentary, the sector outlook. It is not an immediate purchase. These are not real stocks.&lt;/p&gt;

&lt;h2&gt;
  
  
  A short checklist before you act on a low
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Find the reason. Read the last two quarterly results and any exchange filings. If you cannot explain the fall in one sentence, do not buy.&lt;/li&gt;
&lt;li&gt;Is it the stock or the market? A stock falling alone is a bigger warning than one falling with its sector and the Nifty.&lt;/li&gt;
&lt;li&gt;Is return on capital still intact? ROCE still above about 15%, and not falling sharply.&lt;/li&gt;
&lt;li&gt;Is the balance sheet safe? Debt to equity low and stable; interest well covered by operating profit.&lt;/li&gt;
&lt;li&gt;No rising pledge or promoter selling? Check the latest shareholding pattern on NSE or BSE.&lt;/li&gt;
&lt;li&gt;Earnings trend: one bad quarter is noise; three or four in a row is a trend.&lt;/li&gt;
&lt;li&gt;Is the valuation honestly lower, with stable earnings, or only because profits fell?&lt;/li&gt;
&lt;li&gt;Has the selling stopped? Prefer stocks that have stopped making new lows and are holding a base for a few weeks, over ones still sliding.&lt;/li&gt;
&lt;li&gt;Size small, and decide in advance the price or business event that proves you wrong.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Buying near a 52-week low is a contrarian bet that the market has been too harsh on a sound business. Buying near a 52-week high is a momentum bet that a strong trend will continue. Studies of the 52-week-high effect, covered in MultibaggerLab's &lt;a href="https://www.multibaggerlab.com/blog-stocks-near-52-week-high" rel="noopener noreferrer"&gt;guide to stocks near their 52-week high&lt;/a&gt;, have found that, on average, stocks near their highs did better than stocks far below them. That is a useful warning for low-hunters. A stock at its low is, on average, fighting the trend. You need a clear business reason to expect it to turn, and the patience to wait.&lt;/p&gt;

&lt;p&gt;The full version of this guide is at &lt;a href="https://www.multibaggerlab.com/blog-stocks-at-52-week-low" rel="noopener noreferrer"&gt;Stocks at 52-Week Low: How to Tell an Opportunity from a Value Trap&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;MultibaggerLab is not a SEBI-registered Investment Adviser or Research Analyst. Nothing here is investment advice or a stock recommendation. The worked example uses hypothetical numbers. This is educational content only. Always do your own research.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>investing</category>
      <category>finance</category>
      <category>stocks</category>
      <category>beginners</category>
    </item>
    <item>
      <title>What a Good Debt-to-Equity Ratio Looks Like, and When Banks Break the Rule</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 10:01:28 +0000</pubDate>
      <link>https://dev.to/algosimplified/what-a-good-debt-to-equity-ratio-looks-like-and-when-banks-break-the-rule-389f</link>
      <guid>https://dev.to/algosimplified/what-a-good-debt-to-equity-ratio-looks-like-and-when-banks-break-the-rule-389f</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://www.multibaggerlab.com/blog-debt-to-equity-ratio" rel="noopener noreferrer"&gt;MultibaggerLab&lt;/a&gt;. That URL is canonical. The full guide has a longer FAQ, sector asides and a Screener.in query you can paste. This is a shorter, restructured cut of the same explainer.&lt;/p&gt;

&lt;p&gt;For most non-financial companies, a good debt-to-equity ratio is below 1, and below 0.5 is conservative. Above 2 is high risk unless the business is a utility or infrastructure asset with contracted cash flows. Banks and NBFCs sit in a different world: 6 to 10 times is normal for a lender. The rest of this note is about what the number is measuring, when a high reading is a problem, and what to check beside it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two kinds of money, one ratio
&lt;/h2&gt;

&lt;p&gt;Every company is funded in two ways. Owners put money in and leave profits in. That is equity. The company also borrows. That is debt. The debt-to-equity ratio measures the balance:&lt;/p&gt;

&lt;p&gt;Debt-to-equity = total debt Ã· total shareholders' equity&lt;/p&gt;

&lt;p&gt;Total debt is short-term plus long-term borrowings on the balance sheet. Shareholders' equity is share capital plus reserves and surplus, the capital that belongs to the owners.&lt;/p&gt;

&lt;p&gt;A worked example. A company has â‚¹400 crore of borrowings and â‚¹800 crore of shareholders' equity. Its D/E is 400 Ã· 800 = 0.5. For every â‚¹1 of owners' capital, it carries 50 paise of debt. If borrowings were â‚¹1,200 crore against the same â‚¹800 crore of equity, D/E would be 1.5. Now there is more debt than equity in the business.&lt;/p&gt;

&lt;p&gt;Many investors prefer net debt to equity, which subtracts cash from debt first. A company with â‚¹400 crore of borrowings and â‚¹350 crore of cash has a gross D/E of 0.5 but a net D/E of about 0.06. When a company sits on a large cash pile, the net figure is the fairer one.&lt;/p&gt;

&lt;p&gt;Some screeners and annual reports show D/E as a percentage. Multiply by 100: a D/E of 0.5 is 50%, and 1.5 is 150%. The meaning does not change.&lt;/p&gt;

&lt;h2&gt;
  
  
  A working range, not a single "ideal" number
&lt;/h2&gt;

&lt;p&gt;There is no single right figure. It depends on how steady the company's cash flows are. As a rough guide for non-financial companies:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;D/E&lt;/th&gt;
&lt;th&gt;What it usually means&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;0 (debt-free)&lt;/td&gt;
&lt;td&gt;No borrowings. Survives almost any downturn. Still check whether the business can grow.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Below 0.5&lt;/td&gt;
&lt;td&gt;Conservative. Comfortable through a full economic cycle.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;0.5 to 1.0&lt;/td&gt;
&lt;td&gt;Moderate. Fine for a business with steady, predictable cash flows.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1.0 to 2.0&lt;/td&gt;
&lt;td&gt;Leveraged. Needs strong, stable earnings and healthy interest coverage.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Above 2.0&lt;/td&gt;
&lt;td&gt;High risk for a non-financial company, unless it is a regulated utility or infrastructure asset with contracted cash flows.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Sector matters a lot. Utilities, roads, telecom and real estate are built on long-life assets and often run D/E above 1. That is normal for them. Comparing a power-transmission company with an FMCG company tells you nothing. Always compare within a sector. The trend over 3 to 5 years matters as much as today's level.&lt;/p&gt;

&lt;h2&gt;
  
  
  What a high D/E actually changes
&lt;/h2&gt;

&lt;p&gt;A high D/E means a large part of the business is funded by borrowing. Debt is not bad in itself. Used well, it lets a good business grow faster than profits alone would allow. It does change the risk in three ways.&lt;/p&gt;

&lt;p&gt;It magnifies results both ways. Borrowed money lifts return on equity in good years and deepens losses in bad ones. The margin for error is smaller.&lt;/p&gt;

&lt;p&gt;Interest is a fixed cost. It must be paid on time, good quarter or bad. A company can skip a dividend. It cannot skip an interest payment without risking default.&lt;/p&gt;

&lt;p&gt;Loans have to be rolled over. Most corporate debt is refinanced, not repaid. When credit gets tight or the company's story wobbles, refinancing can get expensive, or vanish.&lt;/p&gt;

&lt;p&gt;This is why a heavily indebted small-cap is one of the riskiest things a retail investor can own. The story can still be good, and the stock can still go to zero, because shareholders are last in line when debt cannot be paid.&lt;/p&gt;

&lt;h2&gt;
  
  
  The checks that belong next to D/E
&lt;/h2&gt;

&lt;p&gt;D/E tells you how much debt there is. Two more numbers tell you whether that debt is a problem.&lt;/p&gt;

&lt;p&gt;Interest coverage = operating profit (EBIT) Ã· interest expense. You generally want this above 3, and above 5 is comfortable. Near or below 1.5, almost all operating profit goes to lenders. A company can have a moderate D/E but weak coverage if profits are thin, so check both.&lt;/p&gt;

&lt;p&gt;Also look at the debt maturity profile. How much borrowing falls due in the next 12 months? A moderate D/E with a big chunk due next year, in a tight credit market, is more fragile than it looks. The annual report notes break this down. When policy rates rise, companies with a high D/E usually feel it first through a bigger interest bill.&lt;/p&gt;

&lt;h2&gt;
  
  
  Banks, and the debt-free trap
&lt;/h2&gt;

&lt;p&gt;For a bank or NBFC, borrowing is the business. It takes in deposits and wholesale funding and lends the money out at a higher rate. A D/E of roughly 6 to 10 times is normal for a lender and does not signal distress. Skip D/E for financial companies. Judge them on capital adequacy, net interest margin and asset quality (gross and net NPAs, and provision coverage) instead.&lt;/p&gt;

&lt;p&gt;A truly debt-free company has real advantages. It can ride out a long downturn without a lender forcing its hand. More operating profit flows to shareholders. And it can borrow cheaply if a good opportunity comes along.&lt;/p&gt;

&lt;p&gt;But "debt-free" is a filter, not a reason to buy. A debt-free company in a shrinking industry is still a bad business. Some of the best compounders use a small, well-covered amount of debt to fund growth that earns far more than the interest cost. A company can also be debt-free on paper and still carry large off-balance-sheet obligations such as leases, guarantees or contingent liabilities. Read the notes.&lt;/p&gt;

&lt;p&gt;Low debt can hide a different cost too. Loss-making growth companies often raise fresh equity instead of borrowing. That keeps D/E low but shrinks your share of the company.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why a falling ratio can matter more than a low one
&lt;/h2&gt;

&lt;p&gt;One pattern shows up often in Indian stocks: the deleveraging re-rating. When a heavily indebted company pays debt down over two or three years, three things tend to happen. Interest costs fall, so profit can rise even if operations are flat. The risk of distress fades, so the market may pay a higher multiple. And management can focus on growth instead of survival. So it is worth screening for companies where D/E is trending down, not just low today.&lt;/p&gt;

&lt;p&gt;A conservative starting screen is: debt to equity below 0.5, interest coverage above 4, five-year profit growth above 10%, return on capital employed above 15%, and five-year sales growth above 8%. For a debt-free-only list, tighten the first line to D/E below 0.05. For possible deleveraging stories, loosen D/E to below 1, then check the five-year borrowings trend on each company's page. Leave banks and NBFCs out of any D/E screen. The ratio is not comparable for them.&lt;/p&gt;

&lt;p&gt;The full version, with the paste-ready Screener.in query and a longer FAQ, is in the &lt;a href="https://www.multibaggerlab.com/blog-debt-to-equity-ratio" rel="noopener noreferrer"&gt;canonical MultibaggerLab guide to the debt-to-equity ratio&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;MultibaggerLab is not a SEBI-registered Investment Adviser or Research Analyst. Nothing here is investment advice or a stock recommendation. This is educational content only. Always do your own research.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>investing</category>
      <category>finance</category>
      <category>stocks</category>
      <category>beginners</category>
    </item>
    <item>
      <title>There Is No 'Good' PE Ratio. There Are Only Three Comparisons</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 09:56:26 +0000</pubDate>
      <link>https://dev.to/algosimplified/there-is-no-good-pe-ratio-there-are-only-three-comparisons-gd4</link>
      <guid>https://dev.to/algosimplified/there-is-no-good-pe-ratio-there-are-only-three-comparisons-gd4</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://www.multibaggerlab.com/blog-pe-ratio-explained" rel="noopener noreferrer"&gt;MultibaggerLab&lt;/a&gt;. That URL is canonical. The full guide has a longer checklist, a Screener.in starting block and a link to the live Nifty PE page. This is a shorter, restructured cut of the same explainer.&lt;/p&gt;

&lt;p&gt;The PE ratio is usually the first number people look at on a stock, and the one they most often misread. It is not a rule that says "buy below 15, sell above 30." A PE on its own is like a person's weight with no idea of their height. It only starts to mean something when you compare it with the company's own history, its peers, and its growth.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the number is actually saying
&lt;/h2&gt;

&lt;p&gt;Imagine a small shop earns â‚¹1 lakh of profit a year. If someone offered to sell you that shop for â‚¹20 lakh, you would be paying 20 times its annual earnings. At today's profit, it would take 20 years of earnings to get your money back. That "20 times" is the PE ratio.&lt;/p&gt;

&lt;p&gt;A listed company works the same way. The PE is the market's price tag on the company's profit, expressed as a multiple. A stock on a PE of 10 is cheaper relative to what it earns than one on a PE of 50. Cheaper is not the same as better. That is where most of the confusion starts.&lt;/p&gt;

&lt;h2&gt;
  
  
  The formula, and one place people go wrong
&lt;/h2&gt;

&lt;p&gt;There are two ways to calculate it, and they give the same answer:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;PE = market price per share Ã· earnings per share (EPS)&lt;/li&gt;
&lt;li&gt;PE = total market capitalisation Ã· total annual net profit&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A worked example. A company's shares trade at â‚¹500. Over the last twelve months it earned â‚¹25 of profit per share. Its PE is 500 Ã· 25 = 20. Equivalently, if it has 10 crore shares, its market cap is â‚¹5,000 crore and its annual net profit is â‚¹250 crore, and 5,000 Ã· 250 is also 20.&lt;/p&gt;

&lt;p&gt;You rarely need to do this by hand, because every broker app shows a PE. What matters is knowing which earnings sit in the denominator.&lt;/p&gt;

&lt;p&gt;If you want to check the app's number, add up net profit after tax for the last four reported quarters (trailing twelve months), use consolidated figures if the company has subsidiaries, then divide the current price by that EPS. Then sanity-check the profit. Strip out one-off gains such as asset sales or tax write-backs.&lt;/p&gt;

&lt;p&gt;A second example shows why that last step matters. A company made â‚¹120 crore of net profit over the last four quarters and has 6 crore shares. EPS = 120 Ã· 6 = â‚¹20. At a share price of â‚¹360, PE = 360 Ã· 20 = 18. If â‚¹30 crore of that profit came from selling a building, core EPS is â‚¹15 and the real PE is 24.&lt;/p&gt;

&lt;h2&gt;
  
  
  Flip the PE and you get earnings yield
&lt;/h2&gt;

&lt;p&gt;Turn the PE upside down and you get earnings yield: 1 Ã· PE. A PE of 20 is a 5% earnings yield. A PE of 40 is 2.5%. That makes it easier to compare a stock or an index with a bond yield or a fixed deposit, on the same footing. If the bond pays more than the stock currently earns, you are betting on growth to close the gap.&lt;/p&gt;

&lt;p&gt;As a market-level reference: the Nifty 50 PE was 20.49 at the close on 13 November 2026, down from 22.31 a year earlier (NSE index close files). That is an earnings yield of about 4.9%. The &lt;a href="https://www.multibaggerlab.com/blog-nifty-pe-ratio" rel="noopener noreferrer"&gt;Nifty PE ratio page&lt;/a&gt; on MultibaggerLab tracks the latest official reading.&lt;/p&gt;

&lt;h2&gt;
  
  
  Trailing, forward, and the index PE
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Type&lt;/th&gt;
&lt;th&gt;Earnings used&lt;/th&gt;
&lt;th&gt;When it helps&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Trailing PE (TTM)&lt;/td&gt;
&lt;td&gt;The last four reported quarters, actual numbers&lt;/td&gt;
&lt;td&gt;The default. Backward-looking, but reliable.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Forward PE&lt;/td&gt;
&lt;td&gt;An estimate of next year's earnings&lt;/td&gt;
&lt;td&gt;Useful when trailing profit understates a fast-growing business, and only as good as the estimate.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Index PE (for example the Nifty 50 PE)&lt;/td&gt;
&lt;td&gt;Combined earnings of the index constituents&lt;/td&gt;
&lt;td&gt;A rough gauge of whether the whole market is expensive or cheap versus its own history.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The Nifty 50's PE has historically spent most of its time in the high teens to low 20s, spiking higher near market tops and falling into the mid-teens or below in bad years. Treat it as a temperature check, not a timing signal.&lt;/p&gt;

&lt;h2&gt;
  
  
  The three comparisons that make a PE useful
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Versus the company's own history. If a stock has traded between a PE of 15 and 25 for a decade and it is now at 12, that is interesting. If it is now at 40, the market is expecting something the company has not delivered before.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Versus its sector and close peers. FMCG and software companies structurally trade at higher PEs than metals or utilities, because their earnings are steadier and need less capital. Comparing an IT company's PE with a cement company's PE tells you nothing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Versus its growth rate. That is the PEG ratio: PE Ã· earnings growth %. A PE of 30 on a company growing profit at 30% a year is a PEG of 1. A PE of 30 on a company growing at 8% is a PEG of nearly 4. Same PE, very different situations.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A rough band, with large caveats, for a typical non-financial company:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;PE band&lt;/th&gt;
&lt;th&gt;A cautious reading&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Under 10&lt;/td&gt;
&lt;td&gt;Cheap on the surface. Often a cyclical near a profit peak, a business in decline, or a stock the market distrusts. Sometimes a genuine bargain.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;10 to 20&lt;/td&gt;
&lt;td&gt;A common zone for a steady, moderately growing company.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;20 to 40&lt;/td&gt;
&lt;td&gt;The market expects above-average growth. Reasonable for a genuinely high-quality compounder; risky if the growth is only a hope.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Above 40&lt;/td&gt;
&lt;td&gt;Priced for years of near-flawless execution. Can work for a rare franchise. Leaves no margin for error.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Fast-growing, high-ROCE, asset-light businesses can legitimately earn higher PEs. Deep cyclicals often look cheapest exactly when they are most dangerous, at the top of the cycle.&lt;/p&gt;

&lt;h2&gt;
  
  
  The two mistakes that do most of the damage
&lt;/h2&gt;

&lt;p&gt;The first is assuming a high PE means overvalued. A high PE means the market expects strong growth. If that growth shows up, today's PE was justified. Many of the best-performing Indian stocks of the last decade looked expensive on PE for years, because the earnings kept compounding into the multiple. The real danger with a high PE is not the number itself. It is that a single disappointing quarter can trigger a sharp fall, because there was no cushion.&lt;/p&gt;

&lt;p&gt;The second is assuming a low PE means cheap. That is the value trap. A stock trades at a PE of 6 for a reason, usually a reason the market has already worked out. Falling market share, a promoter problem, a regulated business with capped returns, or a cyclical whose earnings are about to roll over. A low PE is an invitation to investigate, not a conclusion.&lt;/p&gt;

&lt;h2&gt;
  
  
  When the PE ratio is the wrong tool
&lt;/h2&gt;

&lt;p&gt;The PE is useless or misleading in several common situations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Negative or near-zero earnings. Dividing price by a loss gives a negative or absurdly high PE that means nothing. Use EV/EBITDA or price-to-sales instead.&lt;/li&gt;
&lt;li&gt;One-off gains in the earnings. A land or subsidiary sale can crush the PE for a year. Check whether the profit is from the core business.&lt;/li&gt;
&lt;li&gt;Banks and NBFCs. The market values lenders on price-to-book and return on equity, not PE.&lt;/li&gt;
&lt;li&gt;Deep cyclicals. Commodities, metals, sugar or cement at the top of a cycle post record profits, so the PE looks tiny, right before earnings normalise. Here a low PE is a warning.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A short checklist before you rely on the number: is the company profitable? Is it trailing or forward, consolidated or standalone? Any one-off in the profit? How does it compare with the stock's own 5 to 10 year PE range, and with three or four close peers? What is the PEG, and is the growth real or a forecast? If it is a bank, an NBFC or a deep cyclical, lean on price-to-book or cycle-adjusted earnings instead.&lt;/p&gt;

&lt;p&gt;The full version, including a starting Screener.in block and a longer FAQ, is in the &lt;a href="https://www.multibaggerlab.com/blog-pe-ratio-explained" rel="noopener noreferrer"&gt;canonical MultibaggerLab guide to the PE ratio&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;MultibaggerLab is not a SEBI-registered Investment Adviser or Research Analyst. Nothing here is investment advice or a stock recommendation. This is educational content only. Always do your own research.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>investing</category>
      <category>finance</category>
      <category>stocks</category>
      <category>beginners</category>
    </item>
    <item>
      <title>A Multibagger Is a Return, Not a Share Price</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 09:55:38 +0000</pubDate>
      <link>https://dev.to/algosimplified/a-multibagger-is-a-return-not-a-share-price-2o6i</link>
      <guid>https://dev.to/algosimplified/a-multibagger-is-a-return-not-a-share-price-2o6i</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://www.multibaggerlab.com/blog-what-is-multibagger" rel="noopener noreferrer"&gt;MultibaggerLab&lt;/a&gt;. That URL is canonical. The full guide has the screening walk-through, the penny-stock comparison and related reading. This is a shorter, restructured cut of the same explainer.&lt;/p&gt;

&lt;p&gt;People often talk about a "multibagger stock" as if it were a category, like a large-cap or a penny stock. It is not. The word describes a return after the fact. A stock is a 10-bagger only once â‚¹1 lakh has become â‚¹10 lakh. Until then, it is just a company with a price.&lt;/p&gt;

&lt;p&gt;That distinction matters in India, where the phrase gets used as a promise. The useful work is to understand the maths, the size constraint, and the risks that the highlight reels leave out.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the "bags" actually mean
&lt;/h2&gt;

&lt;p&gt;A multibagger is a stock that multiplies your original investment. The bags are simply the multiple:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Return&lt;/th&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;2x&lt;/td&gt;
&lt;td&gt;2-bagger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5x&lt;/td&gt;
&lt;td&gt;5-bagger&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;10x&lt;/td&gt;
&lt;td&gt;10-bagger (what most people mean by "multibagger")&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The quiet phrase in that definition is "over time." Genuine compounding of this kind usually takes years, not weeks. A stock that 10x in a few months is almost always a speculative spike, and those moves tend to give the gain back just as fast.&lt;/p&gt;

&lt;h2&gt;
  
  
  The maths is CAGR times time, not daily circuits
&lt;/h2&gt;

&lt;p&gt;Two levers decide the end result: the return you earn each year, and how long you stay invested. A rough picture of a 10x:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;25% CAGR takes about 10 years&lt;/li&gt;
&lt;li&gt;35% CAGR takes about 7 years&lt;/li&gt;
&lt;li&gt;50% CAGR takes about 5 years&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nothing in that table requires an upper circuit every day. The long compounding stories are often boring for long stretches, with the sharp moves compressed into certain phases of a cycle. Most genuine multibaggers play out over 5 to 10 years, somewhere in that 25% to 50% CAGR band.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why most of these stories start small
&lt;/h2&gt;

&lt;p&gt;Can a Reliance or a TCS still 10x from here? It is possible. The probability is lower simply because of the size required. It is mathematically easier for a â‚¹5,000 crore company to become â‚¹50,000 crore than for a â‚¹15 lakh crore company to become â‚¹1.5 crore crore.&lt;/p&gt;

&lt;p&gt;That is why most real multibaggers start in the small-cap or mid-cap space, or as leaders in a sector where the total opportunity is still expanding. This is not a new pattern. Names that are large-cap household brands today, such as Eicher Motors, Bajaj Finance, Titan and Page Industries, were relatively unknown mid-caps or small-caps a decade or two ago.&lt;/p&gt;

&lt;p&gt;The uncomfortable part follows from that. By the time a stock is widely recognised as a great company, most of the multiplication has usually already happened. The work, such as it is, is in studying a business before the story is obvious, not in buying whatever is already trending.&lt;/p&gt;

&lt;p&gt;Large caps can still compound well over long periods. A true 10x-in-a-decade outcome is just statistically more common further down the market-cap ladder.&lt;/p&gt;

&lt;h2&gt;
  
  
  Shared traits, not a treasure map
&lt;/h2&gt;

&lt;p&gt;Patterns are never perfect. Many big winners have still tended to share a few ingredients:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Earnings that compound steadily, not just one lucky year&lt;/li&gt;
&lt;li&gt;An industry that is expanding, not shrinking&lt;/li&gt;
&lt;li&gt;A starting valuation that has not already priced in the dream&lt;/li&gt;
&lt;li&gt;A clean balance sheet: manageable debt and transparent accounts&lt;/li&gt;
&lt;li&gt;Management that is competent and aligned, with a track record you can check&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That list does not mean every stock with these traits will 10x. It only means you are hunting in a more sensible place than a tip on a message group.&lt;/p&gt;

&lt;p&gt;If you want a process, start with a screen, not a tip. Filter listed companies for consistent revenue and profit growth over 3 to 5 years, a healthy return on equity, manageable debt, and a valuation that has not already run far ahead of the business. Then read the annual report and the concall transcripts. The screen narrows the list. It does not make the decision.&lt;/p&gt;

&lt;h2&gt;
  
  
  The risks the highlight reels skip
&lt;/h2&gt;

&lt;p&gt;"Multibagger" hides a blunt fact. Many attempts never get there. Some go to zero. A few double and then roll back. Survivorship bias makes it look as if everyone who held a famous winner became wealthy, when thousands of other ideas quietly failed along the way.&lt;/p&gt;

&lt;p&gt;The risks worth respecting:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Liquidity in very small caps, where exiting a meaningful size is hard&lt;/li&gt;
&lt;li&gt;Concentration in a single name, to the point that you cannot sleep&lt;/li&gt;
&lt;li&gt;A story that keeps rising while the earnings do not&lt;/li&gt;
&lt;li&gt;Regulatory or governance shocks&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A penny stock is a different idea altogether. It is defined by a low share price, and usually by a small market capitalisation and thin volume. A multibagger is defined only by the return it eventually delivers. Some penny stocks do become multibaggers. Most stay penny stocks, or go to zero. A low price, on its own, tells you nothing about business quality.&lt;/p&gt;

&lt;h2&gt;
  
  
  A better question than "which stock will 10x?"
&lt;/h2&gt;

&lt;p&gt;A more useful framing is this: can you build a process that occasionally delivers multibaggers, without blowing up the rest of the capital?&lt;/p&gt;

&lt;p&gt;That usually means a solid base in index funds or quality large caps, only a portion of the portfolio in more aggressive ideas, a checklist before buying, and some exit logic written down in advance. Position size and diversification matter more here than almost anywhere else in a portfolio, because the failure rate is higher.&lt;/p&gt;

&lt;p&gt;The full version, including how this sits next to a screening checklist and a risk-management framework, is in the &lt;a href="https://www.multibaggerlab.com/blog-what-is-multibagger" rel="noopener noreferrer"&gt;canonical MultibaggerLab guide on what a multibagger is&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;MultibaggerLab is not a SEBI-registered Investment Adviser or Research Analyst. Nothing here is investment advice or a stock recommendation. This is educational content only. Always do your own research.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>investing</category>
      <category>finance</category>
      <category>stocks</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Kafka Architecture Explained: Brokers, Partitions, KRaft</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 09:49:47 +0000</pubDate>
      <link>https://dev.to/algosimplified/kafka-architecture-explained-brokers-partitions-kraft-259o</link>
      <guid>https://dev.to/algosimplified/kafka-architecture-explained-brokers-partitions-kraft-259o</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://algosimplified.dev/posts/kafka-architecture/" rel="noopener noreferrer"&gt;AlgoSimplified&lt;/a&gt;. That URL is canonical. The full post has the architecture diagram, the combined-mode config, sizing notes and a longer FAQ. This is a shorter cut of the same article.&lt;/p&gt;

&lt;p&gt;The related course lesson is &lt;a href="https://algosimplified.dev/courses/kafka-mastery/01-fundamentals/" rel="noopener noreferrer"&gt;Kafka Fundamentals and Architecture&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;A Kafka cluster is a set of &lt;strong&gt;brokers&lt;/strong&gt; that store &lt;strong&gt;topics&lt;/strong&gt;. Each topic is split into &lt;strong&gt;partitions&lt;/strong&gt;, every partition is copied to a few brokers, and a &lt;strong&gt;controller quorum&lt;/strong&gt; tracks which replica leads each partition. Producers append to partition leaders; consumers read from them in &lt;strong&gt;consumer groups&lt;/strong&gt;. Ordering, scaling, failover and delivery guarantees all follow from those pieces.&lt;/p&gt;

&lt;p&gt;Every command output below was copied from a real three-node Kafka 4.4 cluster. The run includes stopping one broker to see what happens on failover.&lt;/p&gt;

&lt;h2&gt;
  
  
  The pieces
&lt;/h2&gt;

&lt;p&gt;A &lt;a href="https://algosimplified.dev/images/posts/kafka-architecture-diagram.svg" rel="noopener noreferrer"&gt;diagram of this layout&lt;/a&gt; is on the original post. Read it left to right:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Producers&lt;/strong&gt; decide which partition each record goes to (by hashing the key) and send it to that partition's &lt;strong&gt;leader&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Brokers&lt;/strong&gt; store partitions as append-only logs on disk. Each partition has one leader and some &lt;strong&gt;followers&lt;/strong&gt; that copy it.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;controller quorum&lt;/strong&gt; stores the cluster's metadata (which brokers are alive, which replica leads each partition) and tells brokers about changes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Consumers&lt;/strong&gt; in a group split the partitions between them and read each one in order, tracking their position with &lt;strong&gt;offsets&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A broker is one Kafka server process. A cluster is a set of brokers that share the same metadata. Clients only need one or two broker addresses (&lt;code&gt;bootstrap.servers&lt;/code&gt;). They fetch the full cluster metadata from there and then talk directly to whichever broker leads each partition they need. There is no central proxy in the data path, which is one reason Kafka scales.&lt;/p&gt;

&lt;h2&gt;
  
  
  Topics, partitions and offsets
&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;topic&lt;/strong&gt; is a named stream of records, like &lt;code&gt;orders&lt;/code&gt; or &lt;code&gt;payments&lt;/code&gt;. A topic is split into &lt;strong&gt;partitions&lt;/strong&gt;, and each partition is an ordered, append-only log. Each record in a partition gets a sequential &lt;strong&gt;offset&lt;/strong&gt;: 0, 1, 2 and so on.&lt;/p&gt;

&lt;p&gt;Two consequences matter in practice:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Ordering is per partition, not per topic.&lt;/strong&gt; Records with the same key land in the same partition, so all events for one key stay in order. There is no global order across partitions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Partitions are the unit of parallelism.&lt;/strong&gt; One partition is read by at most one consumer in a group, so a topic with 6 partitions can keep at most 6 consumers in one group busy.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The same rule on the test cluster: seven records with four different keys, written to a 3-partition topic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ &lt;span class="nb"&gt;printf&lt;/span&gt; &lt;span class="s1"&gt;'alice:p1\nbob:p2\ncarol:p3\ndave:p4\nalice:p5\nbob:p6\nalice:p7\n'&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; \
    kafka-console-producer.sh --bootstrap-server localhost:9092 --topic payments \
      --reader-property parse.key=true --reader-property key.separator=:

$ kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic payments \
    --from-beginning --group billing \
    --formatter-property print.partition=true --formatter-property print.offset=true \
    --formatter-property print.key=true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Partition:0 Offset:0    alice   p1
Partition:0 Offset:1    bob p2
Partition:0 Offset:2    alice   p5
Partition:0 Offset:3    bob p6
Partition:0 Offset:4    alice   p7
Partition:1 Offset:0    dave    p4
Partition:2 Offset:0    carol   p3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every &lt;code&gt;alice&lt;/code&gt; record went to partition 0, in the order it was sent; offsets restart at 0 in each partition. Notice too that &lt;code&gt;alice&lt;/code&gt; and &lt;code&gt;bob&lt;/code&gt; share a partition: hashing spreads keys, but it does not guarantee an even spread with only a few keys. Records &lt;strong&gt;without&lt;/strong&gt; a key are spread by the producer's sticky partitioner, which fills a batch for one partition before moving to the next.&lt;/p&gt;

&lt;h2&gt;
  
  
  Replication, ISR and acks
&lt;/h2&gt;

&lt;p&gt;Each partition is stored on &lt;code&gt;replication.factor&lt;/code&gt; brokers. One replica is the &lt;strong&gt;leader&lt;/strong&gt;: all writes go to it, and by default all reads too. The others are &lt;strong&gt;followers&lt;/strong&gt; that continuously fetch from the leader.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;in-sync replicas (ISR)&lt;/strong&gt; are the replicas that are caught up with the leader. A follower that falls behind for longer than &lt;code&gt;replica.lag.time.max.ms&lt;/code&gt; (30 seconds by default) drops out. Only an in-sync replica can be elected leader without losing acknowledged data.&lt;/p&gt;

&lt;p&gt;This is the &lt;code&gt;orders&lt;/code&gt; topic on the test cluster, created with 3 partitions and replication factor 3:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Topic: orders   TopicId: 4B3TSKlDRtCdKi47DG0fwg PartitionCount: 3   ReplicationFactor: 3    Configs: min.insync.replicas=2
    Topic: orders   Partition: 0    Leader: 2   Replicas: 2,3,1 Isr: 2,3,1  Elr:    LastKnownElr:
    Topic: orders   Partition: 1    Leader: 3   Replicas: 3,1,2 Isr: 3,1,2  Elr:    LastKnownElr:
    Topic: orders   Partition: 2    Leader: 1   Replicas: 1,2,3 Isr: 1,2,3  Elr:    LastKnownElr:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Leadership is spread so each broker leads one partition here. All three replicas are in sync. &lt;code&gt;Elr&lt;/code&gt; (eligible leader replicas, KIP-966) is empty because nothing has failed yet.&lt;/p&gt;

&lt;p&gt;The producer's &lt;code&gt;acks&lt;/code&gt; setting decides when a write counts as successful: &lt;code&gt;0&lt;/code&gt; means the producer does not wait, &lt;code&gt;1&lt;/code&gt; means the leader has written it, &lt;code&gt;all&lt;/code&gt; means every replica in the ISR has it. &lt;code&gt;acks=all&lt;/code&gt; on its own is not enough: if the ISR shrinks to just the leader, "all in-sync replicas" means one copy. That is what &lt;code&gt;min.insync.replicas&lt;/code&gt; is for. With replication factor 3 and &lt;code&gt;min.insync.replicas=2&lt;/code&gt;, an &lt;code&gt;acks=all&lt;/code&gt; write needs at least two copies, so the topic keeps accepting writes with one broker down and rejects them (with &lt;code&gt;NotEnoughReplicas&lt;/code&gt;) if two are down. Since Kafka 3.0, producers default to &lt;code&gt;acks=all&lt;/code&gt; with idempotence on.&lt;/p&gt;

&lt;p&gt;Consumers can only read records below the &lt;strong&gt;high watermark&lt;/strong&gt; â€” the offset up to which every ISR member has the data â€” which is why a record acknowledged with &lt;code&gt;acks=all&lt;/code&gt; survives a leader failure.&lt;/p&gt;

&lt;h2&gt;
  
  
  The controller and KRaft
&lt;/h2&gt;

&lt;p&gt;Something has to decide which replica leads each partition, notice when a broker dies, and keep the topic list. That is the &lt;strong&gt;controller&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Older Kafka used ZooKeeper for this. Since &lt;strong&gt;Kafka 4.0&lt;/strong&gt;, ZooKeeper is gone entirely and every cluster runs in &lt;strong&gt;KRaft&lt;/strong&gt; mode: a small group of controller nodes (usually 3, or 5 for very large clusters) runs Raft over an internal log called &lt;code&gt;__cluster_metadata&lt;/code&gt;. One controller is &lt;strong&gt;active&lt;/strong&gt;; the others are hot standbys. On the test cluster:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ClusterId:              hzBgkkuDRbyx9OM67laWUA
LeaderId:               2
LeaderEpoch:            1
HighWatermark:          142
MaxFollowerLag:         0
MaxFollowerLagTimeMs:   176
CurrentVoters:          [{"id": 1, "endpoints": ["CONTROLLER://localhost:19091"]}, {"id": 2, "endpoints": ["CONTROLLER://localhost:19092"]}, {"id": 3, "endpoints": ["CONTROLLER://localhost:19093"]}]
CurrentObservers:       []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;LeaderId: 2&lt;/code&gt; is the active controller. Raft needs a majority of voters, so 3 controllers tolerate 1 failure and 5 tolerate 2. In production, controllers usually run as separate processes from brokers. The test cluster used combined mode (&lt;code&gt;process.roles=broker,controller&lt;/code&gt;), which is fine for development. The original post has the full properties file.&lt;/p&gt;

&lt;h2&gt;
  
  
  Write path and read path
&lt;/h2&gt;

&lt;p&gt;On &lt;code&gt;send()&lt;/code&gt;, the record is serialized and assigned a partition (by key hash, or by the sticky partitioner if it has no key), added to an in-memory &lt;strong&gt;batch&lt;/strong&gt;, and sent to the partition leader. Followers fetch the new records. Once every ISR member has them, they sit below the high watermark and the leader replies to an &lt;code&gt;acks=all&lt;/code&gt; producer.&lt;/p&gt;

&lt;p&gt;Consumers &lt;strong&gt;pull&lt;/strong&gt;. Kafka does not delete records when they are read, so many independent applications can read the same topic, each at its own pace. A &lt;strong&gt;consumer group&lt;/strong&gt; shares a &lt;code&gt;group.id&lt;/code&gt;; Kafka assigns each partition to exactly one member. If a consumer joins or dies, partitions are reassigned (a rebalance). Lag â€” &lt;code&gt;LOG-END-OFFSET&lt;/code&gt; minus &lt;code&gt;CURRENT-OFFSET&lt;/code&gt; â€” is the single most useful Kafka health metric.&lt;/p&gt;

&lt;p&gt;Kafka 4.0 also made the new consumer rebalance protocol (KIP-848) generally available. Clients opt in with &lt;code&gt;group.protocol=consumer&lt;/code&gt;, and the broker then computes assignments incrementally, so a rebalance no longer pauses the whole group.&lt;/p&gt;

&lt;h2&gt;
  
  
  What happens when a broker fails
&lt;/h2&gt;

&lt;p&gt;On the test cluster, broker 2 was both the leader of &lt;code&gt;orders-0&lt;/code&gt; and the active controller. About 15 seconds after stopping it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Topic: orders   TopicId: 4B3TSKlDRtCdKi47DG0fwg PartitionCount: 3   ReplicationFactor: 3    Configs: min.insync.replicas=2
    Topic: orders   Partition: 0    Leader: 3   Replicas: 2,3,1 Isr: 3,1    Elr:    LastKnownElr:
    Topic: orders   Partition: 1    Leader: 3   Replicas: 3,1,2 Isr: 3,1    Elr:    LastKnownElr:
    Topic: orders   Partition: 2    Leader: 1   Replicas: 1,2,3 Isr: 1,3    Elr:    LastKnownElr:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;LeaderId:               1
LeaderEpoch:            2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three things happened automatically:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Controller failover.&lt;/strong&gt; The two remaining controllers elected node 1 as the new active controller (epoch 1 â†’ 2).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Partition leader election.&lt;/strong&gt; The new controller noticed broker 2 had stopped heartbeating and made broker 3, the next in-sync replica, leader of &lt;code&gt;orders-0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;ISR shrink.&lt;/strong&gt; Broker 2 was removed from every ISR.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Writes kept working: an &lt;code&gt;acks=all&lt;/code&gt; produce succeeded because two in-sync replicas still met &lt;code&gt;min.insync.replicas=2&lt;/code&gt;. Clients found the new leader on their own by refreshing metadata.&lt;/p&gt;

&lt;p&gt;After restarting broker 2, it caught up and rejoined every ISR within about 20 seconds. Broker 3 still led partition 0 for a while; Kafka moves leadership back to the preferred replica on its own a few minutes later (&lt;code&gt;auto.leader.rebalance.enable&lt;/code&gt;, checked every 5 minutes by default). A later &lt;code&gt;--describe&lt;/code&gt; on the test cluster showed &lt;code&gt;Partition: 0  Leader: 2&lt;/code&gt; again.&lt;/p&gt;

&lt;h2&gt;
  
  
  A few points that are easy to miss
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Kafka 4.0 removed ZooKeeper support. Older clusters must migrate to KRaft on a 3.x release before upgrading to 4.x.&lt;/li&gt;
&lt;li&gt;Order is guaranteed within a partition, not across partitions. Give related events the same key.&lt;/li&gt;
&lt;li&gt;Brokers hold partition data and serve clients. Controllers hold cluster metadata and run leader elections. A node can be either, or both in combined mode.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;a href="https://algosimplified.dev/posts/kafka-architecture/" rel="noopener noreferrer"&gt;full architecture article&lt;/a&gt; has the diagram, the combined-mode config, and the sizing table. From there: the free &lt;a href="https://algosimplified.dev/courses/kafka-mastery/" rel="noopener noreferrer"&gt;Kafka Mastery course&lt;/a&gt;, starting with &lt;a href="https://algosimplified.dev/courses/kafka-mastery/01-fundamentals/" rel="noopener noreferrer"&gt;fundamentals&lt;/a&gt;, plus &lt;a href="https://algosimplified.dev/posts/kafka-partitions/" rel="noopener noreferrer"&gt;partitions&lt;/a&gt; and &lt;a href="https://algosimplified.dev/courses/kafka-mastery/05-lag-management/" rel="noopener noreferrer"&gt;consumer lag&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>kafka</category>
      <category>programming</category>
      <category>architecture</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Rate Limiter System Design and Algorithms</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 09:44:14 +0000</pubDate>
      <link>https://dev.to/algosimplified/rate-limiter-system-design-and-algorithms-224b</link>
      <guid>https://dev.to/algosimplified/rate-limiter-system-design-and-algorithms-224b</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://algosimplified.dev/courses/system-design/11-design-rate-limiter/" rel="noopener noreferrer"&gt;AlgoSimplified&lt;/a&gt;. That URL is canonical. The full lesson has the exercises and a short quiz; this is a shorter cut of the same design.&lt;/p&gt;

&lt;p&gt;There is a full system-design lesson for this, rather than an LLD one. The Redis course also has a smaller sliding-window and token-bucket section; the design below is the HLD case study.&lt;/p&gt;

&lt;h2&gt;
  
  
  The problem
&lt;/h2&gt;

&lt;p&gt;Design a service that limits how many requests a client can make, for example 100 requests per minute per API key. It protects services from abuse and overload, enforces pricing tiers, and keeps one noisy customer from hurting the rest.&lt;/p&gt;

&lt;p&gt;A reasonable set of requirements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Limit by a key (user id, API key, IP) with per-rule limits (&lt;code&gt;/login&lt;/code&gt;: 5/min per IP; API: 1,000/min per key).&lt;/li&gt;
&lt;li&gt;Reject excess requests with &lt;strong&gt;429 Too Many Requests&lt;/strong&gt; and a &lt;code&gt;Retry-After&lt;/code&gt; header.&lt;/li&gt;
&lt;li&gt;Low added latency (a millisecond or two), and correct behaviour across many API servers.&lt;/li&gt;
&lt;li&gt;If the limiter itself fails, &lt;strong&gt;fail open&lt;/strong&gt; (let traffic through) rather than taking the whole API down, for most endpoints.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It belongs in an &lt;strong&gt;API gateway&lt;/strong&gt; or in middleware, consulting a &lt;strong&gt;shared store&lt;/strong&gt; (Redis) so all servers agree on the counts. Client-side limits are a courtesy, not enforcement.&lt;/p&gt;

&lt;h2&gt;
  
  
  The algorithms
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Fixed window counter.&lt;/strong&gt; Count requests per key per calendar minute. Simple and cheap. The flaw is at the boundary: a client can send 100 requests at 0:59 and 100 at 1:00, which is 200 in two seconds.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sliding window log.&lt;/strong&gt; Store each request's timestamp and count those in the last 60 seconds. Exact, but memory grows with traffic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sliding window counter.&lt;/strong&gt; Keep counts for the current and previous fixed windows and weight the previous one by how much of it still overlaps the rolling window. Nearly exact, with two counters per key.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Token bucket.&lt;/strong&gt; A bucket holds up to &lt;code&gt;capacity&lt;/code&gt; tokens and refills at &lt;code&gt;rate&lt;/code&gt; per second; each request takes one. This allows short bursts up to capacity while enforcing the average rate, which is what many cloud APIs do.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Leaky bucket.&lt;/strong&gt; Requests enter a queue drained at a fixed rate, which smooths the outflow completely. A good fit when the downstream can only take a steady stream.&lt;/p&gt;

&lt;p&gt;The two implementations below are the ones I use most often, run with a fake clock so the output is deterministic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="s2"&gt;"""Two rate limiters: token bucket and sliding-window counter."""&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TokenBucket&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Allows bursts up to `capacity`, refills at `rate` tokens per second."""&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;monotonic&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tokens&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;allow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tokens&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tokens&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;rate&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tokens&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tokens&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SlidingWindowCounter&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Approximates a rolling window using the current and previous fixed windows."""&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;window&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;monotonic&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;window&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;window&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;current_start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;previous&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;allow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;window&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;current_start&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="c1"&gt;# moved into a new window; previous only counts if it was the adjacent one&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;previous&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;current_start&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;window&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;current_start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;
        &lt;span class="n"&gt;overlap&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;window&lt;/span&gt;  &lt;span class="c1"&gt;# fraction of previous window still in view&lt;/span&gt;
        &lt;span class="n"&gt;estimated&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;previous&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;overlap&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;estimated&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;FakeClock&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__call__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"__main__"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;clock&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FakeClock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;bucket&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;TokenBucket&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rate&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;clock&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;burst&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;bucket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"token bucket, 7 instant requests:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;burst&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;clock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"after 2 s:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;bucket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;clock&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FakeClock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;sw&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;SlidingWindowCounter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;window&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;clock&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;clock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;50&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"sliding window, 10 at t=50s:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sw&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"allowed"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;clock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;70&lt;/span&gt;  &lt;span class="c1"&gt;# new window; 10/60 of it elapsed, so ~83% of last window still counts&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"12 more at t=70s:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sw&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"allowed"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;token bucket, 7 instant requests: [True, True, True, True, True, False, False]
after 2 s: [True, True, False]
sliding window, 10 at t=50s: 10 allowed
12 more at t=70s: 2 allowed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The bucket allows a burst of 5, then refills 2 tokens in 2 seconds. The sliding window remembers that 10 requests happened 20 seconds ago in the previous window and only admits 2 more, which is how it avoids the fixed-window boundary burst.&lt;/p&gt;

&lt;h2&gt;
  
  
  Distributed design
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;client -&amp;gt; load balancer -&amp;gt; API gateway (limiter middleware) -&amp;gt; services
                                |
                                v
                         Redis cluster (counters, sharded by key)
                                ^
                         rules config (loaded and cached by gateways)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The check and update in Redis &lt;strong&gt;must be atomic&lt;/strong&gt;. Otherwise two gateways read "99", both allow, and the count becomes 101. Two options that work:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;INCR key&lt;/code&gt; then &lt;code&gt;EXPIRE key 60&lt;/code&gt; for fixed windows (INCR is atomic; set the expiry when the value is 1).&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;Lua script&lt;/strong&gt; that reads, computes and writes the token bucket in one step on the Redis server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each check is one round trip (around 0.5 ms in the same data centre). Shard counters across Redis nodes by key.&lt;/p&gt;

&lt;p&gt;When one Redis call per request starts to hurt:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Local pre-aggregation:&lt;/strong&gt; each gateway keeps a small local budget and syncs with Redis every few hundred milliseconds. Slightly less accurate, with far fewer Redis calls.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Multi-region:&lt;/strong&gt; keep limits per region (the simplest option), or sync asynchronously and accept slight over-admission.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hot keys:&lt;/strong&gt; one very large customer can get a dedicated Redis shard.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Failure handling
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;If Redis is unreachable, fail open (with an alarm) for ordinary APIs; fail closed for security-sensitive ones like login or password reset.&lt;/li&gt;
&lt;li&gt;Return headers so clients can back off cleanly: &lt;code&gt;X-RateLimit-Limit&lt;/code&gt;, &lt;code&gt;X-RateLimit-Remaining&lt;/code&gt;, &lt;code&gt;Retry-After&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Log rejected requests. A spike of 429s is an early signal of abuse or a buggy client.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;a href="https://algosimplified.dev/courses/system-design/11-design-rate-limiter/" rel="noopener noreferrer"&gt;full rate limiter lesson&lt;/a&gt; also has exercises (a sliding-window log, the Redis Lua token bucket, tiered limits) and a short quiz. It is part of the free &lt;a href="https://algosimplified.dev/courses/system-design/" rel="noopener noreferrer"&gt;System Design course&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>python</category>
      <category>redis</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>LRU Cache (LeetCode 146) Design in Python and Java</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 09:38:27 +0000</pubDate>
      <link>https://dev.to/algosimplified/lru-cache-leetcode-146-design-in-python-and-java-2g9o</link>
      <guid>https://dev.to/algosimplified/lru-cache-leetcode-146-design-in-python-and-java-2g9o</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://algosimplified.dev/courses/low-level-design/09-design-lru-cache/" rel="noopener noreferrer"&gt;AlgoSimplified&lt;/a&gt;. That URL is canonical. The full lesson has the complete Java class, follow-up sketches, exercises and a short quiz. This is a shorter cut of the same design.&lt;/p&gt;

&lt;h2&gt;
  
  
  The problem
&lt;/h2&gt;

&lt;p&gt;A cache with fixed capacity. &lt;code&gt;get(key)&lt;/code&gt; returns the value (or a miss) and marks the key as recently used. &lt;code&gt;put(key, value)&lt;/code&gt; inserts or updates; if the cache is full, it evicts the &lt;strong&gt;least recently used&lt;/strong&gt; key. Both operations must be O(1).&lt;/p&gt;

&lt;p&gt;A hash map gives O(1) lookup but no order. A list gives order, but moving an item to the front is O(n) unless you can reach its neighbours directly.&lt;/p&gt;

&lt;p&gt;The combination that works is a hash map from key to node, plus a doubly linked list ordered from most to least recently used. The map finds the node; the links let you unlink it and move it in O(1).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;head &amp;lt;-&amp;gt; [4] &amp;lt;-&amp;gt; [3] &amp;lt;-&amp;gt; tail
          MRU           LRU
map = {4: node4, 3: node3}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sentinel head and tail nodes remove the empty-list special cases. Every real node always has non-null neighbours.&lt;/p&gt;

&lt;h2&gt;
  
  
  Python
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="s2"&gt;"""LRU cache with O(1) get and put: hash map + doubly linked list."""&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;__slots__&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"key"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"value"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"prev"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"next"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LRUCache&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;ValueError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"capacity must be positive"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;capacity&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;map&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;  &lt;span class="c1"&gt;# key -&amp;gt; Node&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tail&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# sentinels: head.next is most recent&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tail&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tail&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_unlink&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prev&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prev&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_push_front&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prev&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prev&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;default&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;default&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_unlink&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# mark as most recently used&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_push_front&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_unlink&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_push_front&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;map&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;lru&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tail&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prev&lt;/span&gt;  &lt;span class="c1"&gt;# least recently used sits just before the tail&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_unlink&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;lru&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;del&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;map&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lru&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;map&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_push_front&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;keys_mru_to_lru&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;head&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tail&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"__main__"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;LRUCache&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"one"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"two"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;           &lt;span class="c1"&gt;# one  (1 becomes most recent)&lt;/span&gt;
    &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"three"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;         &lt;span class="c1"&gt;# evicts 2&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;           &lt;span class="c1"&gt;# -1&lt;/span&gt;
    &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"four"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;          &lt;span class="c1"&gt;# evicts 1&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# -1 three four&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"order:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;keys_mru_to_lru&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;one
-1
-1 three four
order: [4, 3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After &lt;code&gt;get(1)&lt;/code&gt;, key 1 is most recent, so &lt;code&gt;put(3)&lt;/code&gt; evicts 2, not 1. After &lt;code&gt;put(4)&lt;/code&gt;, 1 is gone and the list is 4 then 3.&lt;/p&gt;

&lt;h2&gt;
  
  
  Java
&lt;/h2&gt;

&lt;p&gt;The Java in the &lt;a href="https://algosimplified.dev/courses/low-level-design/09-design-lru-cache/" rel="noopener noreferrer"&gt;full lesson&lt;/a&gt; is the same structure, generic over key and value: sentinel head and tail, &lt;code&gt;HashMap&amp;lt;K, Node&amp;lt;K, V&amp;gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;unlink&lt;/code&gt; and &lt;code&gt;pushFront&lt;/code&gt;, with &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;put&lt;/code&gt; marked &lt;code&gt;synchronized&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Two differences are worth noting:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A miss returns &lt;code&gt;null&lt;/code&gt;, not &lt;code&gt;-1&lt;/code&gt;. The run prints &lt;code&gt;one&lt;/code&gt;, then &lt;code&gt;null&lt;/code&gt;, then &lt;code&gt;null three four&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;synchronized&lt;/code&gt; makes each method atomic. A read/write lock would not help: &lt;code&gt;get&lt;/code&gt; also rewrites the list, so every operation is a write to the ordering.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The lesson records that same output from &lt;code&gt;javac&lt;/code&gt; / &lt;code&gt;java LRUCache&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Library shortcuts and common follow-ups
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Python: &lt;code&gt;collections.OrderedDict&lt;/code&gt; with &lt;code&gt;move_to_end(key)&lt;/code&gt; and &lt;code&gt;popitem(last=False)&lt;/code&gt;; &lt;code&gt;functools.lru_cache&lt;/code&gt; for memoising functions.&lt;/li&gt;
&lt;li&gt;Java: &lt;code&gt;LinkedHashMap&lt;/code&gt; with &lt;code&gt;accessOrder=true&lt;/code&gt; and an overridden &lt;code&gt;removeEldestEntry&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In interviews, it is usually enough to mention the shortcut, then implement the linked list unless you are told otherwise.&lt;/p&gt;

&lt;p&gt;Common follow-ups:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Throughput:&lt;/strong&gt; one lock serialises everything. Shard by key hash into N segments, each with its own lock and capacity (approximate LRU, much higher throughput).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;TTL:&lt;/strong&gt; store an expiry on the node; treat expired entries as misses, and optionally sweep in the background.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;LFU:&lt;/strong&gt; evict the least frequently used key. An O(1) design keeps a map of frequency to a doubly linked list, plus a &lt;code&gt;min_freq&lt;/code&gt; pointer.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Distributed cache:&lt;/strong&gt; that becomes an HLD question. The &lt;a href="https://algosimplified.dev/courses/system-design/04-caching/" rel="noopener noreferrer"&gt;caching lesson&lt;/a&gt; in the System Design course covers that side. Redis itself offers approximate LRU eviction.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is also LeetCode 146, and it appears on the &lt;a href="https://algosimplified.dev/leetcode-150/" rel="noopener noreferrer"&gt;LeetCode 150 sheet&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The list has to be doubly linked, because unlinking in O(1) needs a pointer to the previous node. The &lt;a href="https://algosimplified.dev/courses/low-level-design/09-design-lru-cache/" rel="noopener noreferrer"&gt;full LRU lesson&lt;/a&gt; has the complete Java, exercises (TTL, a sharded cache, LFU) and a short quiz, as part of the free &lt;a href="https://algosimplified.dev/courses/low-level-design/" rel="noopener noreferrer"&gt;Low-Level Design course&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>python</category>
      <category>java</category>
      <category>leetcode</category>
      <category>programming</category>
    </item>
    <item>
      <title>Parking Lot Low-Level Design (LLD) with Python Code</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 09:38:12 +0000</pubDate>
      <link>https://dev.to/algosimplified/parking-lot-low-level-design-lld-with-python-code-2gjl</link>
      <guid>https://dev.to/algosimplified/parking-lot-low-level-design-lld-with-python-code-2gjl</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://algosimplified.dev/courses/low-level-design/07-design-parking-lot/" rel="noopener noreferrer"&gt;AlgoSimplified&lt;/a&gt;. That URL is canonical. The full lesson has the class diagram, the complete Python, exercises and a short quiz. This is a shorter cut of the same design.&lt;/p&gt;

&lt;p&gt;Parking lot is a common low-level design interview problem. The useful work at the start is to fix the scope, separate the two policies that change from lot to lot, and make the find-and-occupy path atomic.&lt;/p&gt;

&lt;h2&gt;
  
  
  A reasonable interview scope
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Several floors, each with spots in three sizes: small (motorcycle), medium (car), large (truck or bus).&lt;/li&gt;
&lt;li&gt;A vehicle may use a spot of its size or a larger one.&lt;/li&gt;
&lt;li&gt;On entry, issue a ticket with the spot and the entry time; reject the vehicle when nothing fits.&lt;/li&gt;
&lt;li&gt;On exit, compute an hourly fee (rate depends on vehicle type; partial hours round up, minimum one hour) and free the spot.&lt;/li&gt;
&lt;li&gt;Several entry and exit gates run at the same time.&lt;/li&gt;
&lt;li&gt;A display board needs free-spot counts.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Leave payments, reservations, EV charging and valet as extensions unless the interviewer asks for them.&lt;/p&gt;

&lt;p&gt;Nouns: &lt;code&gt;ParkingLot&lt;/code&gt;, &lt;code&gt;Floor&lt;/code&gt;, &lt;code&gt;Spot&lt;/code&gt;, &lt;code&gt;Vehicle&lt;/code&gt;, &lt;code&gt;VehicleType&lt;/code&gt;, &lt;code&gt;Ticket&lt;/code&gt;, &lt;code&gt;Gate&lt;/code&gt;, &lt;code&gt;PricingStrategy&lt;/code&gt;, &lt;code&gt;Payment&lt;/code&gt;, &lt;code&gt;DisplayBoard&lt;/code&gt;. Verbs: park, leave, findSpot, calculateFee, countFree.&lt;/p&gt;

&lt;h2&gt;
  
  
  Policies that vary
&lt;/h2&gt;

&lt;p&gt;Two policies change from lot to lot:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How a spot is chosen: nearest to the entrance, lowest floor, smallest fit, reserved EV spots. That is a &lt;code&gt;SpotAllocator&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;How a stay is priced: hourly, flat daily, weekend rates, monthly passes. That is a &lt;code&gt;PricingStrategy&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both are injected into &lt;code&gt;ParkingLot&lt;/code&gt;, so a mall and an airport can share the same core.&lt;/p&gt;

&lt;p&gt;Rules that do not vary: a spot is free or holds exactly one vehicle; a plate has at most one open ticket; &lt;code&gt;park&lt;/code&gt; and &lt;code&gt;leave&lt;/code&gt; must be atomic, or two gates will hand out the same spot.&lt;/p&gt;

&lt;p&gt;The live lesson has a Mermaid class diagram of this. In short, &lt;code&gt;ParkingLot&lt;/code&gt; owns floors of spots, talks to a &lt;code&gt;SpotAllocator&lt;/code&gt; and a &lt;code&gt;PricingStrategy&lt;/code&gt;, and keeps open tickets keyed by plate.&lt;/p&gt;

&lt;h2&gt;
  
  
  The design in Python
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="s2"&gt;"""Parking lot low-level design: multi-floor, spot sizes, tickets and pricing."""&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;itertools&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;math&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;threading&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;abc&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="no"&gt;ABC&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;abstractmethod&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;dataclasses&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dataclass&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;enum&lt;/span&gt; &lt;span class="nf"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Enum&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Enum&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="no"&gt;SMALL&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;   &lt;span class="c1"&gt;# motorcycle&lt;/span&gt;
    &lt;span class="no"&gt;MEDIUM&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;  &lt;span class="c1"&gt;# car&lt;/span&gt;
    &lt;span class="no"&gt;LARGE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;   &lt;span class="c1"&gt;# bus / truck&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VehicleType&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Enum&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="no"&gt;MOTORCYCLE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SMALL&lt;/span&gt;
    &lt;span class="no"&gt;CAR&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;MEDIUM&lt;/span&gt;
    &lt;span class="no"&gt;TRUCK&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;LARGE&lt;/span&gt;


&lt;span class="nd"&gt;@dataclass&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;frozen&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Vehicle&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;plate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;
    &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;VehicleType&lt;/span&gt;


&lt;span class="nd"&gt;@dataclass&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Spot&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;
    &lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;
    &lt;span class="n"&gt;vehicle&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Vehicle&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;fits&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Vehicle&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;vehicle&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;


&lt;span class="nd"&gt;@dataclass&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Floor&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;
    &lt;span class="n"&gt;spots&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Spot&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;


&lt;span class="nd"&gt;@dataclass&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Ticket&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;
    &lt;span class="n"&gt;vehicle&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Vehicle&lt;/span&gt;
    &lt;span class="n"&gt;spot&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Spot&lt;/span&gt;
    &lt;span class="n"&gt;entry_hour&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;
    &lt;span class="n"&gt;exit_hour&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
    &lt;span class="n"&gt;fee&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PricingStrategy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;ABC&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nd"&gt;@abstractmethod&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;fee&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ticket&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Ticket&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hours&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;HourlyPricing&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PricingStrategy&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="no"&gt;RATES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nc"&gt;VehicleType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;MOTORCYCLE&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;VehicleType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;CAR&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;VehicleType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;TRUCK&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;fee&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ticket&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hours&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;billable&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ceil&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hours&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# first hour always charged, then per started hour&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;billable&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;RATES&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;ticket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;vehicle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SpotAllocator&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;ABC&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nd"&gt;@abstractmethod&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;floors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Floor&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Vehicle&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Spot&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SmallestFitFirst&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SpotAllocator&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Lowest floor first, and the smallest spot that fits, so big spots stay free for big vehicles."""&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;floors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;floor&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;floors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;candidates&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;floor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;spots&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fits&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;candidates&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;candidates&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ParkingFullError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Exception&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;pass&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ParkingLot&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;floors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;allocator&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;SpotAllocator&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pricing&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;PricingStrategy&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;floors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;allocator&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pricing&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;floors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;allocator&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pricing&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;active&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Ticket&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;  &lt;span class="c1"&gt;# plate -&amp;gt; open ticket&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_ids&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;itertools&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_lock&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;threading&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Lock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# entry gates run concurrently&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;park&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Vehicle&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Ticket&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_lock&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;plate&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;active&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;ValueError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{v.plate} is already parked"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;spot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;allocator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;floors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;spot&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;ParkingFullError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"no spot for {v.type.name}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;spot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;vehicle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;
            &lt;span class="n"&gt;ticket&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Ticket&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_ids&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;spot&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;active&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;plate&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ticket&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ticket&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;leave&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;plate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Ticket&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_lock&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;ticket&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;active&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;plate&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;ticket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exit_hour&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;
            &lt;span class="n"&gt;ticket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;fee&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pricing&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fee&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ticket&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;ticket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;entry_hour&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;ticket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;spot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;vehicle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ticket&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;free_spots&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;counts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;floors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;spots&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;vehicle&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;counts&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;counts&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"__main__"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;floors&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Floor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Spot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"0-S1"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SMALL&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Spot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"0-M1"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;MEDIUM&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Spot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"0-L1"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;LARGE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
              &lt;span class="nc"&gt;Floor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Spot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"1-M1"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;MEDIUM&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Spot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"1-M2"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Size&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;MEDIUM&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;lot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ParkingLot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;floors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;SmallestFitFirst&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;HourlyPricing&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;t1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;lot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;park&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Vehicle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"KA01"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;VehicleType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;CAR&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;9.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;t2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;lot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;park&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Vehicle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"KA02"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;VehicleType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;MOTORCYCLE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;9.5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;t3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;lot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;park&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Vehicle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"KA03"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;VehicleType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;TRUCK&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;10.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;t1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;t2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;t3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"ticket {t.id}: {t.vehicle.plate} -&amp;gt; spot {t.spot.id}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;lot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;park&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Vehicle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"KA04"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;VehicleType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;TRUCK&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;10.5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;ParkingFullError&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"rejected:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;done&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;lot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;leave&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"KA01"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;11.25&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"KA01 paid Rs {done.fee} for {done.exit_hour - done.entry_hour} h"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"free:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;lot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;free_spots&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;items&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ticket 1: KA01 -&amp;gt; spot 0-M1
ticket 2: KA02 -&amp;gt; spot 0-S1
ticket 3: KA03 -&amp;gt; spot 0-L1
rejected: no spot for TRUCK
KA01 paid Rs 90 for 2.25 h
free: {'SMALL': 0, 'MEDIUM': 3, 'LARGE': 0}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What the run shows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;VehicleType&lt;/code&gt; maps each vehicle to the minimum size it needs, so &lt;code&gt;Spot.fits&lt;/code&gt; is one comparison.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;SmallestFitFirst&lt;/code&gt; scans from the lowest floor and picks the smallest fitting spot. The car took the medium spot even though the large one was free, which is the point of the policy: keep large spots for trucks.&lt;/li&gt;
&lt;li&gt;The second truck is rejected with a domain exception, not a &lt;code&gt;None&lt;/code&gt; the caller might ignore.&lt;/li&gt;
&lt;li&gt;KA01 stayed 2.25 hours. Per-started-hour billing is 3 hours Ã— Rs 30 = Rs 90.&lt;/li&gt;
&lt;li&gt;One lock wraps "find, occupy, record the ticket". Without it, two gates can both see &lt;code&gt;0-M1&lt;/code&gt; free and both assign it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Scaling the design
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Finding a spot in O(1): keep a free-spot set or min-heap per size per floor. &lt;code&gt;park&lt;/code&gt; pops, &lt;code&gt;leave&lt;/code&gt; pushes back.&lt;/li&gt;
&lt;li&gt;Finer locking: one lock per size class or per floor, with a consistent lock order so you don't deadlock.&lt;/li&gt;
&lt;li&gt;Persistence: the "find and occupy" step becomes a conditional update (&lt;code&gt;UPDATE spot SET plate=? WHERE id=? AND plate IS NULL&lt;/code&gt;) so the database picks one winner.&lt;/li&gt;
&lt;li&gt;Display boards can subscribe to spot changes (observer).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In an interview, it helps to spend the first few minutes on requirements, draw the classes before coding, name the two strategies, and raise concurrency without being prompted.&lt;/p&gt;

&lt;p&gt;The class diagram, exercises (free-spot sets, flat daily pricing, EV spots that do not touch &lt;code&gt;ParkingLot&lt;/code&gt;) and a short quiz are in the &lt;a href="https://algosimplified.dev/courses/low-level-design/07-design-parking-lot/" rel="noopener noreferrer"&gt;full parking lot lesson&lt;/a&gt;, part of the free &lt;a href="https://algosimplified.dev/courses/low-level-design/" rel="noopener noreferrer"&gt;Low-Level Design course&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>python</category>
      <category>interview</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Blind 75 vs NeetCode 150 vs Grind 75</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 09:32:09 +0000</pubDate>
      <link>https://dev.to/algosimplified/blind-75-vs-neetcode-150-vs-grind-75-4k5c</link>
      <guid>https://dev.to/algosimplified/blind-75-vs-neetcode-150-vs-grind-75-4k5c</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://algosimplified.dev/blind-75-vs-neetcode-150/" rel="noopener noreferrer"&gt;AlgoSimplified&lt;/a&gt;. That page is the canonical version.&lt;/p&gt;

&lt;p&gt;Blind 75, Grind 75 and NeetCode 150 are the lists most people reach for when they want a focused set of LeetCode problems. They are not the same length, they are not the same 75 or 150 problems, and NeetCode 150 is easy to confuse with LeetCode's own Top Interview 150. Below is a comparison of the counts, the overlap and a straightforward way to choose one list.&lt;/p&gt;

&lt;h2&gt;
  
  
  How the lists compare
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://algosimplified.dev/blind-75/" rel="noopener noreferrer"&gt;Blind 75&lt;/a&gt;: 75 problems (19 easy, 49 medium, 7 hard), grouped by topic. About four weeks at three problems a day. A good fit when time is short, or when the aim is to drill one topic at a time.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://algosimplified.dev/grind-75/" rel="noopener noreferrer"&gt;Grind 75&lt;/a&gt;: 75 problems (24 easy, 42 medium, 9 hard), arranged as a week-by-week calendar. The default plan is eight weeks, and the official planner on the Tech Interview Handbook can resize it. A good fit when a schedule, with easier problems first, would help.&lt;/li&gt;
&lt;li&gt;NeetCode 150: 150 problems, organised by pattern. About eight to ten weeks. I have not reproduced the full set here. The list is maintained at &lt;a href="https://neetcode.io/practice" rel="noopener noreferrer"&gt;neetcode.io/practice&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://algosimplified.dev/leetcode-150/" rel="noopener noreferrer"&gt;LeetCode Top Interview 150&lt;/a&gt;: LeetCode's official 150 (40 easy, 92 medium, 18 hard on the AlgoSimplified sheet), tagged by pattern. About eight weeks. This is the list to use when the goal is LeetCode's own interview set, not NeetCode's.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Blind 75 and Grind 75 difficulty counts are from the lists on AlgoSimplified.&lt;/p&gt;

&lt;h2&gt;
  
  
  Blind 75 and Grind 75 share only 40 problems
&lt;/h2&gt;

&lt;p&gt;Yangshun Tay published Blind 75 on the Blind forum in 2018. Grind 75 is his later list: he ranked a larger pool of problems and published a default top 75 as an eight-week calendar.&lt;/p&gt;

&lt;p&gt;I compared the two lists problem by problem. They share 40 of 75. Grind 75 is not Blind 75 in a different order. It drops 35 Blind 75 problems and adds 35 others.&lt;/p&gt;

&lt;p&gt;What Grind 75 adds, in practice: Binary Search and First Bad Version, Flood Fill and Rotting Oranges, stack problems (Min Stack, Evaluate Reverse Polish Notation, Basic Calculator), Time Based Key-Value Store, Task Scheduler, Sort Colors, Subsets, Permutations, and a few more interval and tree problems.&lt;/p&gt;

&lt;p&gt;What it leaves out of Blind 75: the four bit-manipulation problems, Meeting Rooms and Meeting Rooms II, some graph items (Pacific Atlantic Water Flow, Graph Valid Tree, Number of Connected Components), and DP or backtracking problems such as House Robber, House Robber II, Decode Ways and Word Search II.&lt;/p&gt;

&lt;p&gt;If one list is already finished, the remaining work is the other list's 35 extras. Re-solving the shared 40 helps only when those problems can no longer be done cold.&lt;/p&gt;

&lt;h2&gt;
  
  
  What NeetCode 150 covers, and what it does not
&lt;/h2&gt;

&lt;p&gt;For mid-level coding rounds, the 150 is usually sufficient, provided the mediums can be solved in about 25 minutes with a clear account of the approach and its cost. The list covers the patterns those rounds test: hash maps, two pointers, sliding window, stacks, binary search, linked lists, trees, tries, heaps, backtracking, graphs and DP. "Enough" in this context means a whole topic is not missing, not that every interview prompt will come from the list.&lt;/p&gt;

&lt;p&gt;It is not sufficient on its own for low-level or machine-coding rounds, system design or behavioural interviews. A perfect score on the 150 does not prepare you to design a &lt;a href="https://algosimplified.dev/courses/low-level-design/07-design-parking-lot/" rel="noopener noreferrer"&gt;parking lot&lt;/a&gt; or a &lt;a href="https://algosimplified.dev/courses/system-design/11-design-rate-limiter/" rel="noopener noreferrer"&gt;rate limiter&lt;/a&gt;, and those rounds often decide the level. In senior interviews, design and how you lead a discussion tend to weigh more than another 50 LeetCode problems. NeetCode 250 has diminishing returns next to more design practice.&lt;/p&gt;

&lt;p&gt;A useful check is to pick a medium not seen this month and try to solve it in 25 minutes, out loud. If that feels comfortable across arrays, trees, graphs and DP, the list has done its job. If one area is weak, add problems in that area rather than starting a fourth list.&lt;/p&gt;

&lt;h2&gt;
  
  
  A straightforward way to choose
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Interview in the next three weeks.&lt;/strong&gt; &lt;a href="https://algosimplified.dev/blind-75/" rel="noopener noreferrer"&gt;Blind 75&lt;/a&gt;, worked through pattern by pattern, is the usual choice. If week 1 is already full, the matrix problems can wait.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;One to two months, and a schedule is useful.&lt;/strong&gt; The default &lt;a href="https://algosimplified.dev/grind-75/" rel="noopener noreferrer"&gt;Grind 75&lt;/a&gt; plan runs eight weeks. Week 1 is almost all easy (10 easy and 2 medium). The nine hard problems sit in weeks 5 and 7.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;More than two months, or a 75-problem list already finished.&lt;/strong&gt; NeetCode 150, or &lt;a href="https://algosimplified.dev/leetcode-150/" rel="noopener noreferrer"&gt;LeetCode's Top Interview 150&lt;/a&gt; if the official set is the goal. Weak topics can be patched afterwards.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Design rounds are part of the loop.&lt;/strong&gt; Starting &lt;a href="https://algosimplified.dev/courses/low-level-design/" rel="noopener noreferrer"&gt;low-level design&lt;/a&gt; and &lt;a href="https://algosimplified.dev/courses/system-design/" rel="noopener noreferrer"&gt;system design&lt;/a&gt; in parallel from week three leaves more calendar time than leaving them until the coding list is done. The &lt;a href="https://algosimplified.dev/start-here/" rel="noopener noreferrer"&gt;Start here&lt;/a&gt; track lays this out as an eight-week sequence: patterns course, Blind 75, then LLD and system design.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two distinctions that are easy to miss
&lt;/h2&gt;

&lt;p&gt;Blind 75 works well as a four-week refresh when the patterns are already familiar. It is thin on advanced graphs, heaps and hard problems, and it has no design content.&lt;/p&gt;

&lt;p&gt;NeetCode 150 is not the same as &lt;a href="https://algosimplified.dev/leetcode-150/" rel="noopener noreferrer"&gt;LeetCode's Top Interview 150&lt;/a&gt;. The two lists overlap, but they are not the same set.&lt;/p&gt;

&lt;p&gt;The full write-up and the live Blind 75 and Grind 75 lists, with a browser progress tracker and no account required, are on the &lt;a href="https://algosimplified.dev/blind-75-vs-neetcode-150/" rel="noopener noreferrer"&gt;canonical AlgoSimplified page&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>interview</category>
      <category>algorithms</category>
      <category>career</category>
    </item>
    <item>
      <title>Two Pointers Pattern</title>
      <dc:creator>Anurag Goel</dc:creator>
      <pubDate>Thu, 03 Dec 2026 09:31:56 +0000</pubDate>
      <link>https://dev.to/algosimplified/two-pointers-pattern-1b7g</link>
      <guid>https://dev.to/algosimplified/two-pointers-pattern-1b7g</guid>
      <description>&lt;p&gt;This article first appeared on &lt;a href="https://algosimplified.dev/courses/dsa-patterns/02-two-pointers/" rel="noopener noreferrer"&gt;AlgoSimplified&lt;/a&gt;. That URL is canonical. The full lesson has exercises, a short quiz, and a link to a longer two-pointers guide. This is a shorter cut of the same lesson.&lt;/p&gt;

&lt;p&gt;The two-pointers pattern uses two indices that move through a sequence, usually from the ends or in the same direction. Each comparison has to justify discarding one element, which is what keeps the scan linear rather than quadratic.&lt;/p&gt;

&lt;h2&gt;
  
  
  When it applies
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The input is &lt;strong&gt;sorted&lt;/strong&gt; (or you can sort it) and you need pairs or triples with a target sum.&lt;/li&gt;
&lt;li&gt;The problem is &lt;strong&gt;symmetric&lt;/strong&gt;: palindromes, reversing, comparing both ends.&lt;/li&gt;
&lt;li&gt;You need to partition in place (move zeroes, Dutch flag).
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;condition_met&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nf"&gt;record_answer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;need_bigger&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;hi&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each step discards one element for good, so the loop is O(n).&lt;/p&gt;

&lt;h2&gt;
  
  
  Three worked examples
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="s2"&gt;"""Two pointers on sorted or symmetric input."""&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;pair_with_sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sorted_nums&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sorted_nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sorted_nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;sorted_nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;   &lt;span class="c1"&gt;# need a bigger sum: only moving lo right can help&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;hi&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;   &lt;span class="c1"&gt;# need a smaller sum&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;three_sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;out&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;continue&lt;/span&gt;  &lt;span class="c1"&gt;# skip duplicate anchors&lt;/span&gt;
        &lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;hi&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;max_water&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;best&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;best&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;best&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hi&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;lo&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;heights&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;hi&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;lo&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;  &lt;span class="c1"&gt;# the shorter wall limits the area; moving the taller one can't help&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;hi&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;best&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"__main__"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;pair_with_sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;three_sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;max_water&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(2, 3)
[[-1, -1, 2], [-1, 0, 1]]
49
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Why the moves are safe
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Pair sum:&lt;/strong&gt; if &lt;code&gt;a[lo] + a[hi]&lt;/code&gt; is too small, pairing &lt;code&gt;a[lo]&lt;/code&gt; with anything left of &lt;code&gt;hi&lt;/code&gt; is even smaller, so &lt;code&gt;a[lo]&lt;/code&gt; cannot be in any answer. Discard it. That is why the array has to be sorted: moving &lt;code&gt;lo&lt;/code&gt; right increases the sum, moving &lt;code&gt;hi&lt;/code&gt; left decreases it. Here 4 + 6 is the pair at indices &lt;code&gt;(2, 3)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;3Sum:&lt;/strong&gt; sort, fix the first number, then run pair sum on the rest. Skip equal anchors and equal &lt;code&gt;lo&lt;/code&gt; values to avoid duplicate triples, rather than stuffing tuples into a set. O(nÂ²) overall, which is the best known for this problem in practice.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Container with most water:&lt;/strong&gt; the area is limited by the shorter wall. Moving the taller wall inward can only shrink the width without raising that limit, so you always move the shorter one. On &lt;code&gt;[1, 8, 6, 2, 5, 4, 8, 3, 7]&lt;/code&gt; the area is 49.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Related variants
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Same direction (read/write pointers):&lt;/strong&gt; remove duplicates in place, move zeroes. One pointer scans, the other marks where to write.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Opposite ends on strings:&lt;/strong&gt; valid palindrome, reverse vowels.&lt;/li&gt;
&lt;li&gt;When the window between the pointers must satisfy a condition, that's the &lt;a href="https://algosimplified.dev/courses/dsa-patterns/03-sliding-window/" rel="noopener noreferrer"&gt;sliding window&lt;/a&gt; pattern.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For more practice, the &lt;a href="https://algosimplified.dev/dsa-patterns/#two-pointers" rel="noopener noreferrer"&gt;two pointers problems&lt;/a&gt; on the cheat sheet, and the &lt;a href="https://algosimplified.dev/dsa-patterns/two-pointers/" rel="noopener noreferrer"&gt;two pointers technique guide&lt;/a&gt; with eight more worked problems (including trapping rain water and sort colors). The &lt;a href="https://algosimplified.dev/courses/dsa-patterns/02-two-pointers/" rel="noopener noreferrer"&gt;full two pointers lesson&lt;/a&gt; also has exercises (valid palindrome, move zeroes, 4Sum) and a short quiz, as part of the free &lt;a href="https://algosimplified.dev/courses/dsa-patterns/" rel="noopener noreferrer"&gt;DSA Patterns course&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>python</category>
      <category>leetcode</category>
      <category>algorithms</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
