<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Real Dev on Medium]]></title>
        <description><![CDATA[Stories by Real Dev on Medium]]></description>
        <link>https://medium.com/@realdev9868?source=rss-d5fa8071b756------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Real Dev on Medium</title>
            <link>https://medium.com/@realdev9868?source=rss-d5fa8071b756------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 20:46:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@realdev9868/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Most people fail the system design round on the clock, not on knowledge]]></title>
            <link>https://medium.com/@realdev9868/most-people-fail-the-system-design-round-on-the-clock-not-on-knowledge-a4439f94377e?source=rss-d5fa8071b756------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4439f94377e</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Real Dev]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 04:47:19 GMT</pubDate>
            <atom:updated>2026-11-29T04:47:19.541Z</atom:updated>
            <content:encoded><![CDATA[<p>Ask someone who just failed a design round what went wrong and you often hear “I didn’t know enough.” Then ask what they drew. Usually it is a full board: load balancer, cache, queue, a few databases. They knew plenty. They spent it in the wrong order.</p><p>The round is 45 minutes. If you spend 30 of them drawing every component you have read about, you have 15 left for the part the interviewer actually grades, which is how you make and defend one hard decision. So treat the clock as part of the problem.</p><h3>The split</h3><p>Here is the time plan I teach. These are teaching defaults, not a rule from any company. Scale them if your round is 30 or 60 minutes, and keep the shape.</p><pre>Buffer       5 min   greeting, interviewer questions<br>Clarify      5 min   requirements you both agree on<br>Estimate     5 min   a few numbers, and what each one decides<br>High level  10 min   five to eight boxes, one request traced through<br>Deep dive   15 min   one hard part: data, request path, failures, trade-off<br>Wrap up      5 min   decision, risks, next step</pre><p>The deep dive gets the biggest slot on purpose. A short start, a long middle and a firm ending.</p><h3>How to stay on the plan</h3><p>Three habits keep you on time.</p><p>Note the clock time when you begin, up in a corner of the board. Then you never have to guess how long you have been talking.</p><p>Say each transition out loud. “That’s my requirements. Moving to numbers.” It tells the interviewer where you are, and it stops you from drifting back into phase one at minute 20.</p><p>End each phase with a checkpoint. A checkpoint is one short question that hands control back for a moment: “Does this scope match what you had in mind?” or “I think the traffic spike is the hard part. Should I go deep there?” The answer is often a hint. If the interviewer points elsewhere, go there without arguing.</p><h3>What each phase should leave behind</h3><p>A phase is done when it leaves something on the board you can point to later.</p><p>Clarify leaves a short list, split into what the system does and how well it must do it, plus an out-of-scope line. Five to eight questions are enough.</p><p>Estimate leaves a few numbers, and each one has a sentence after it saying what it changes. “10,000 requests a second at peak” is half an answer. “10,000 at peak, and the data never changes, so I’ll serve precomputed pages” is the full one.</p><p>High level leaves the simplest design that meets the list, with a label on every arrow. Then say out loud what is missing from it. That missing piece is usually your deep dive.</p><p>Deep dive leaves one component explained properly: what is stored and how it is keyed, the request path, what fails, and the trade-off you chose.</p><p>Wrap up leaves three sentences: the decision, the risks, and the next thing you would do.</p><h3>A short run-through</h3><p>Prompt: publish Class 12 board results to 10 lakh students at 10 am.</p><p>Clarify. A student types a roll number and sees marks. Results publish once, with a rare correction later. No student login, no marking system. Target: p99 under 1 second at peak, no wrong result ever shown.</p><p>Estimate. Assume each student checks twice in the first 10 minutes:</p><pre>1,000,000 x 2 = 2,000,000 requests / 600 s  = about 3,333 req/s<br>peak factor 3                               = about 10,000 req/s<br>10,000 x 20 KB page                         = 200 MB/s, or 1.6 Gbps</pre><p>Conclusion: all reads, fixed data, a sharp spike. Compute nothing when the request arrives.</p><p>High level. A batch job writes one page per roll number before 10 am. A CDN serves them. Cache misses go through a waiting room to a small result service.</p><p>Deep dive. The 10:00 spike. Warm the CDN with a sample of pages before opening. Let the waiting room admit misses at a safe rate. For a correction, write a new version of that one page and purge only its key. The trade-off is cache lifetime: longer protects the origin, shorter shows corrections sooner.</p><p>Wrap up. Precompute and serve static pages. Risks are a wrong publish and a miss burst. Next step is a load test at three times the estimate.</p><p>Notice how little got drawn. The numbers said the problem was a spike, not a scale problem, so the design stayed small.</p><h3>When the interviewer throws a “what if”</h3><p>Keep the answer local. Restate the change in a single sentence, find the one box it breaks, change one thing, and name the new cost. You do not need to redraw the board for every question.</p><h3>Try it this week</h3><p>Pick three prompts. Run each with a phone timer and talk out loud. Afterwards, check one thing only: did your deep dive start before minute 25? If not, the fix is in your first 20 minutes, not in more reading.</p><p>I wrote the full version of this, with the math script and a sample API, on Dev.to: <a href="https://dev.to/realdev9868/how-to-run-a-45-minute-system-design-interview-a-5-phase-plan-with-one-worked-example-7b0">https://dev.to/realdev9868/how-to-run-a-45-minute-system-design-interview-a-5-phase-plan-with-one-worked-example-7b0</a></p><p>Disclosure: I wrote Think Like a System Designer. Its chapter 32 plays this interview out in full, including a weak and a strong mock transcript. Kindle: <a href="https://www.amazon.com/dp/B0HSST5XZ2">https://www.amazon.com/dp/B0HSST5XZ2</a> · Paperback: <a href="https://www.amazon.com/dp/B0HSSLH69G">https://www.amazon.com/dp/B0HSSLH69G</a> · India (Kindle): <a href="https://www.amazon.in/dp/B0HSST5XZ2">https://www.amazon.in/dp/B0HSST5XZ2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4439f94377e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python’s mutable default argument bug, run one call at a time]]></title>
            <link>https://medium.com/@realdev9868/pythons-mutable-default-argument-bug-run-one-call-at-a-time-136742c0e9f4?source=rss-d5fa8071b756------2</link>
            <guid isPermaLink="false">https://medium.com/p/136742c0e9f4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Real Dev]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 03:48:33 GMT</pubDate>
            <atom:updated>2026-10-27T03:22:55.187Z</atom:updated>
            <content:encoded><![CDATA[<p>This function looks fine. It adds a tag to a list and returns the list. If you don’t pass a list, it starts a new empty one. At least that’s what it seems to do.</p><pre>def add_tag(tag, tags=[]):<br>    tags.append(tag)<br>    return tags</pre><pre>print(add_tag(&quot;python&quot;))<br>print(add_tag(&quot;sql&quot;))<br>print(add_tag(&quot;dsa&quot;, []))<br>print(add_tag(&quot;git&quot;))</pre><pre>[&#39;python&#39;]<br>[&#39;python&#39;, &#39;sql&#39;]<br>[&#39;dsa&#39;]<br>[&#39;python&#39;, &#39;sql&#39;, &#39;git&#39;]</pre><p>The first call is fine. The second call returns [&#39;python&#39;, &#39;sql&#39;], even though we never passed a list. The third call passed its own list, so it got a clean result. Then the fourth call picked up where the second one left off.</p><p>So the “new empty list” is not new. It’s the same list every time you skip the argument.</p><h3>The default is built once</h3><p>Python evaluates a default value when it runs the def line. It does not do it again on each call. The result gets stored on the function object, in __defaults__, and every call that skips the argument gets that one stored object.</p><p>You can look at it directly.</p><pre>def add_tag(tag, tags=[]):<br>    tags.append(tag)<br>    return tags</pre><pre>print(add_tag.__defaults__)<br>first = add_tag(&quot;python&quot;)<br>second = add_tag(&quot;sql&quot;)<br>print(add_tag.__defaults__)<br>print(first is second)<br>print(first is add_tag.__defaults__[0])</pre><pre>([],)<br>([&#39;python&#39;, &#39;sql&#39;],)<br>True<br>True</pre><p>Before any call, the stored default is an empty list. After two calls it holds both tags. first and second are the same object, and that object is the one sitting in __defaults__.</p><p>If you want proof of when the default gets built, put a print inside the code that builds it.</p><pre>def make_default():<br>    print(&quot;  building the default list&quot;)<br>    return []</pre><pre>print(&quot;before def&quot;)</pre><pre>def add_tag(tag, tags=make_default()):<br>    tags.append(tag)<br>    return tags</pre><pre>print(&quot;after def&quot;)<br>add_tag(&quot;a&quot;)<br>add_tag(&quot;b&quot;)<br>print(&quot;after two calls&quot;)</pre><pre>before def<br>  building the default list<br>after def<br>after two calls</pre><p>“building the default list” prints once, between “before def” and “after def”. The two calls don’t print it at all. They reuse what was built when the function was defined.</p><p>This is also why the bug hides in tests. If each test calls the function once, every test passes. It shows up when the same process calls it twice, which is what a web server or a long script does all day.</p><h3>The same bug in a class</h3><p>Classes hit this a lot, because __init__ is just a function with defaults.</p><pre>class Cart:<br>    def __init__(self, items=[]):<br>        self.items = items</pre><pre>    def add(self, item):<br>        self.items.append(item)</pre><pre>asha = Cart()<br>ravi = Cart()<br>asha.add(&quot;notebook&quot;)<br>print(&quot;asha:&quot;, asha.items)<br>print(&quot;ravi:&quot;, ravi.items)<br>print(asha.items is ravi.items)</pre><pre>asha: [&#39;notebook&#39;]<br>ravi: [&#39;notebook&#39;]<br>True</pre><p>Ravi never added anything, but his cart has a notebook. Both carts point at the one list that was built when __init__ was defined. In a real app, that&#39;s one user seeing another user&#39;s data.</p><h3>The fix is None</h3><p>Use None as the default and build the list inside the function. The body runs on every call, so each call gets its own list.</p><pre>def add_tag(tag, tags=None):<br>    if tags is None:<br>        tags = []<br>    tags.append(tag)<br>    return tags</pre><pre>print(add_tag(&quot;python&quot;))<br>print(add_tag(&quot;sql&quot;))<br>mine = [&quot;dsa&quot;]<br>print(add_tag(&quot;git&quot;, mine))<br>print(mine)</pre><pre>[&#39;python&#39;]<br>[&#39;sql&#39;]<br>[&#39;dsa&#39;, &#39;git&#39;]<br>[&#39;dsa&#39;, &#39;git&#39;]</pre><p>Two calls with no list now give two separate results. And when you do pass a list, the function still adds to it, which is what a caller who passes a list usually wants.</p><p>Use if tags is None, not if not tags. The short version looks the same but treats an empty list you passed in as &quot;no list&quot;.</p><pre>def keep_count(tags=None):<br>    tags = tags or []<br>    tags.append(&quot;x&quot;)<br>    return tags</pre><pre>shared = []<br>keep_count(shared)<br>keep_count(shared)<br>print(shared)</pre><pre>[]</pre><p>The caller passed shared and expected two &quot;x&quot; values in it. It&#39;s still empty. An empty list is falsy, so tags or [] threw it away and made a fresh one each time. The appends went into lists nobody kept.</p><h3>Dataclasses refuse to do it</h3><p>If you write the class with @dataclass, Python stops you from making this mistake for a list field.</p><pre>from dataclasses import dataclass, field</pre><pre>try:<br>    @dataclass<br>    class Cart:<br>        items: list = []<br>except ValueError as e:<br>    print(&quot;ValueError:&quot;, e)</pre><pre>@dataclass<br>class Cart:<br>    items: list = field(default_factory=list)</pre><pre>a, b = Cart(), Cart()<br>a.items.append(&quot;pen&quot;)<br>print(a, b)</pre><pre>ValueError: mutable default &lt;class &#39;list&#39;&gt; for field items is not allowed: use default_factory<br>Cart(items=[&#39;pen&#39;]) Cart(items=[])</pre><p>The error happens when the class is defined, so you find out right away. field(default_factory=list) calls list() for each new instance, and the two carts end up with separate lists. Note that the check is not perfect. On 3.13 it rejected list, dict, set and bytearray defaults, but a mutable class of your own can still slip through if it is hashable.</p><h3>When people do it on purpose</h3><p>You will sometimes see a mutable default used as a cache that lives between calls.</p><pre>def fib(n, memo={}):<br>    if n &lt; 2:<br>        return n<br>    if n not in memo:<br>        memo[n] = fib(n - 1) + fib(n - 2)<br>    return memo[n]</pre><pre>print(fib(80))<br>print(len(fib.__defaults__[0]))</pre><pre>23416728348467685<br>79</pre><p>Every result goes into memo, and memo survives between calls. After one call it holds 79 entries.</p><p>It works. But a reader can’t tell if it was on purpose or an accident, and nobody can clear the cache without reaching into __defaults__. functools.lru_cache does the same job and says what it&#39;s doing. If you do keep a trick like this, leave a comment.</p><h3>What to check in your own code</h3><p>Search for =[], ={} and =set() in function signatures. Each one is either a bug waiting for a second call or a cache that needs a comment.</p><p>The same goes for any default that is an object you can change, like a Cart() or a datetime.now() call. The second one isn&#39;t mutable, but it has the same timing problem. It runs once, at definition time, so every call gets the same time.</p><p>When you review code, ask one question about each default value. Is this built once, and is that what we want?</p><p>I work on Schoolabe, a free coding practice site, and small “predict the output” problems like these are what we put in the <a href="https://www.schoolabe.com/logic-building">logic building section</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=136742c0e9f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Python Copy Bug That Looks Fine in Code Review]]></title>
            <link>https://medium.com/@realdev9868/the-python-copy-bug-that-looks-fine-in-code-review-f6bf4fcfb66e?source=rss-d5fa8071b756------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6bf4fcfb66e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Real Dev]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 14:43:13 GMT</pubDate>
            <atom:updated>2026-10-17T14:43:13.467Z</atom:updated>
            <content:encoded><![CDATA[<p>Here is a bug that is easy to ship. A function takes a dict of default settings and hands each new user a copy. Someone adds a tag to one user. Every future user now has that tag too.</p><p>The code looks harmless. Each block below runs on its own, and the output under it is what Python 3.13 printed.</p><pre>defaults = {&quot;theme&quot;: &quot;dark&quot;, &quot;tags&quot;: [&quot;new&quot;]}<br>user_a = defaults.copy()<br>user_a[&quot;tags&quot;].append(&quot;beta&quot;)</pre><pre>print(&quot;1. shallow copy, then append&quot;)<br>print(&quot;   defaults:&quot;, defaults)<br>print(&quot;   user_a  :&quot;, user_a)<br>print(&quot;   same inner list?&quot;, user_a[&quot;tags&quot;] is defaults[&quot;tags&quot;])</pre><pre>1. shallow copy, then append<br>   defaults: {&#39;theme&#39;: &#39;dark&#39;, &#39;tags&#39;: [&#39;new&#39;, &#39;beta&#39;]}<br>   user_a  : {&#39;theme&#39;: &#39;dark&#39;, &#39;tags&#39;: [&#39;new&#39;, &#39;beta&#39;]}<br>   same inner list? True</pre><p>.copy() made a new dict, so user_a is not defaults. But the new dict holds the same list object under &quot;tags&quot;. You copied the outer box and kept pointing at the same contents. That is what &quot;shallow&quot; means. The rest of the interview answer is where it bites.</p><p>When you explain it out loud, draw it: two dict boxes, each with an arrow labelled tags going to the same list box. The drawing usually answers the follow-up questions. The is check in the code is the same picture in text. It asks whether two names point at one object, not whether the contents look equal.</p><p>The same thing happens with the other usual ways to copy. list(x), x[:] and x.copy() all build a new outer list and share the inner ones:</p><pre>nested = [[&quot;a&quot;], [&quot;b&quot;]]<br>clones = [list(nested), nested[:], nested.copy()]<br>print(&quot;inner lists shared with the original:&quot;, [c[0] is nested[0] for c in clones])</pre><pre>inner lists shared with the original: [True, True, True]</pre><p>The bug is not specific to .copy(): it appears wherever you wanted an independent copy and wrote the cheap one.</p><p>Schoolabe’s <a href="https://www.schoolabe.com/python-interview-questions">Python interview questions page</a> lists “What is the difference between shallow copy and deep copy in Python?” in its sample of the question bank. It describes the category as “copying vs references” gotchas that interviewers probe with short follow-ups. Interviewers rarely stop at a definition; they show five lines and ask what prints.</p><h3>Follow-ups worth rehearsing</h3><p>The fix everyone knows is copy.deepcopy, which walks the structure and copies everything it finds:</p><pre>import copy</pre><pre>defaults = {&quot;theme&quot;: &quot;dark&quot;, &quot;tags&quot;: [&quot;new&quot;]}<br>user_b = copy.deepcopy(defaults)<br>user_b[&quot;tags&quot;].append(&quot;beta&quot;)</pre><pre>print(&quot;2. deepcopy, then append&quot;)<br>print(&quot;   defaults:&quot;, defaults)<br>print(&quot;   user_b  :&quot;, user_b)</pre><pre>2. deepcopy, then append<br>   defaults: {&#39;theme&#39;: &#39;dark&#39;, &#39;tags&#39;: [&#39;new&#39;]}<br>   user_b  : {&#39;theme&#39;: &#39;dark&#39;, &#39;tags&#39;: [&#39;new&#39;, &#39;beta&#39;]}</pre><p>Then there is the trap inside the trap: a shallow copy is not always broken. If you replace a value instead of mutating it, the copy is fine.</p><pre>defaults = {&quot;theme&quot;: &quot;dark&quot;, &quot;tags&quot;: [&quot;new&quot;]}<br>user_c = defaults.copy()<br>user_c[&quot;theme&quot;] = &quot;light&quot;<br>user_c[&quot;tags&quot;] = user_c[&quot;tags&quot;] + [&quot;beta&quot;]</pre><pre>print(&quot;3. shallow copy, but rebind instead of mutate&quot;)<br>print(&quot;   defaults:&quot;, defaults)<br>print(&quot;   user_c  :&quot;, user_c)</pre><pre>3. shallow copy, but rebind instead of mutate<br>   defaults: {&#39;theme&#39;: &#39;dark&#39;, &#39;tags&#39;: [&#39;new&#39;]}<br>   user_c  : {&#39;theme&#39;: &#39;light&#39;, &#39;tags&#39;: [&#39;new&#39;, &#39;beta&#39;]}</pre><p>The + builds a brand new list and assigns it to the key in the copy only. append changes the list both dicts share. A small difference in how you write the line decides whether the bug exists, and that is the cause behind advice like &quot;just always use deepcopy&quot;.</p><p>The list-of-lists cousin needs no call to copy at all:</p><pre>grid = [[0] * 3] * 3<br>grid[0][0] = 9<br>print(&quot;repeated rows -&gt;&quot;, grid)</pre><pre>grid = [[0] * 3 for _ in range(3)]<br>grid[0][0] = 9<br>print(&quot;comprehension   -&gt;&quot;, grid)</pre><pre>repeated rows -&gt; [[9, 0, 0], [9, 0, 0], [9, 0, 0]]<br>comprehension   -&gt; [[9, 0, 0], [0, 0, 0], [0, 0, 0]]</pre><p>Multiplying a list repeats the reference, not the row. Three rows, one list. The comprehension fixes it because [0] * 3 is evaluated again for every row, so each row is a fresh list. If someone answers the grid question correctly but can&#39;t say why the comprehension works, keep asking; that is the part that matters. I think this is the better thing to ask in a mock interview, because it tells you more about whether someone understands references than the shallow versus deep definition does. You see it in grid and DP problems, where people build a table of zeros.</p><h3>Is deepcopy just the answer, then?</h3><p>Not by reflex. It copes with cycles, which surprised me: a list that contains itself deep-copies fine, and the last line of the next block checks it. So correctness isn’t the objection. Cost is.</p><pre>import copy<br>import time</pre><pre>rows = [list(range(100)) for _ in range(2000)]<br>times = []<br>for _ in range(10):<br>    start = time.perf_counter()<br>    copy.deepcopy(rows)<br>    times.append((time.perf_counter() - start) * 1000)<br>print(f&quot;deepcopy of 2,000 lists of 100 ints: {min(times):.0f} to {max(times):.0f} ms over 10 runs&quot;)</pre><pre>loop = [1]<br>loop.append(loop)<br>clone = copy.deepcopy(loop)<br>print(&quot;self-referencing list deep-copied fine:&quot;, clone[1] is clone and clone is not loop)</pre><pre>deepcopy of 2,000 lists of 100 ints: 26 to 35 ms over 10 runs<br>self-referencing list deep-copied fine: True</pre><p>(Your timings will differ.)</p><p>That timing is from one machine, so run it yourself. The deepcopy figure held steady across my runs at roughly 25 to 35 ms. I won’t quote a ratio against a shallow copy, because a shallow copy of that list is so quick that the timer mostly measures noise.</p><p>For a settings object copied once per signup, who cares. Inside a loop that runs a million times, you will care a great deal. The cheaper habit is to not share mutable things in the first place: build new lists with + or a comprehension, or store tags as a tuple so append isn&#39;t even possible. Then the shallow copy is safe and you never need the slow one.</p><p>My tests only used lists, dicts and ints. Objects with custom __copy__ or __deepcopy__ methods, or ones holding file handles or locks, behave differently, and I didn&#39;t try any of them. If an interviewer pushes in that direction, say you would check the class before assuming.</p><p>Write down what you think prints before you run it.</p><p><em>Written by the Schoolabe team, who build </em><a href="https://www.schoolabe.com/"><em>schoolabe.com</em></a><em>. Its homepage says tutorials, quizzes and practice are free, and that lessons and practice problems run in the browser.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6bf4fcfb66e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Belady’s Anomaly: FIFO vs LRU vs Optimal, Checked in Python]]></title>
            <link>https://medium.com/@realdev9868/beladys-anomaly-fifo-vs-lru-vs-optimal-checked-in-python-cb86ab2a3be5?source=rss-d5fa8071b756------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb86ab2a3be5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gate]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Real Dev]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 04:55:47 GMT</pubDate>
            <atom:updated>2026-10-20T03:56:09.276Z</atom:updated>
            <content:encoded><![CDATA[<p>Page replacement questions in GATE CS are mostly counting. You get a reference string, a number of frames and a policy, and you write a row of letters. The idea is easy; the marks go when you lose track of the oldest page late in the paper.</p><p>So the useful skill is a method you can run without thinking, plus a way to check yourself on practice problems. I wrote a small Python checker for the second part.</p><p>Schoolabe’s GATE <a href="https://www.schoolabe.com/courses/gate-cs-operating-systems/gate-cs-operating-systems-memory-management">memory management chapter</a> uses this reference string with 3 frames as its worked example:</p><p>1 2 3 4 1 2 5 1 2</p><p>It says to count FIFO carefully with a queue, and it doesn’t print the answer. Here are the three policies, then the numbers. The code blocks in this post are one file, in order; paste them together and it runs.</p><pre>import random<br>from collections import OrderedDict, deque</pre><pre>def fifo(refs, frames):<br>    q, mem, faults, trace = deque(), set(), 0, []<br>    for p in refs:<br>        if p in mem:<br>            trace.append(&quot;hit&quot;)<br>        else:<br>            faults += 1<br>            if len(mem) == frames:<br>                mem.remove(q.popleft())<br>            q.append(p)<br>            mem.add(p)<br>            trace.append(&quot;F&quot;)<br>    return faults, trace</pre><pre>def lru(refs, frames):<br>    mem, faults, trace = OrderedDict(), 0, []<br>    for p in refs:<br>        if p in mem:<br>            mem.move_to_end(p)<br>            trace.append(&quot;hit&quot;)<br>        else:<br>            faults += 1<br>            if len(mem) == frames:<br>                mem.popitem(last=False)<br>            mem[p] = True<br>            trace.append(&quot;F&quot;)<br>    return faults, trace</pre><pre>def opt(refs, frames):<br>    mem, faults, trace = [], 0, []<br>    for i, p in enumerate(refs):<br>        if p in mem:<br>            trace.append(&quot;hit&quot;)<br>            continue<br>        faults += 1<br>        trace.append(&quot;F&quot;)<br>        if len(mem) &lt; frames:<br>            mem.append(p)<br>            continue<br>        rest = refs[i + 1:]<br>        # evict the page whose next use is furthest away (or never)<br>        victim = max(mem, key=lambda x: rest.index(x) if x in rest else float(&quot;inf&quot;))<br>        mem.remove(victim)<br>        mem.append(p)<br>    return faults, trace</pre><pre>lesson = [1, 2, 3, 4, 1, 2, 5, 1, 2]<br>print(&quot;Lesson string with 3 frames:&quot;, lesson)<br>for name, policy in ((&quot;FIFO&quot;, fifo), (&quot;LRU&quot;, lru), (&quot;OPT&quot;, opt)):<br>    n, t = policy(lesson, 3)<br>    print(f&quot;  {name}: {n} faults   {&#39; &#39;.join(t)}&quot;)<br>print(&quot;FIFO on the same string with 4 frames:&quot;, fifo(lesson, 4)[0], &quot;faults&quot;)</pre><pre>Lesson string with 3 frames: [1, 2, 3, 4, 1, 2, 5, 1, 2]<br>  FIFO: 7 faults   F F F F F F F hit hit<br>  LRU: 7 faults   F F F F F F F hit hit<br>  OPT: 5 faults   F F F F hit hit F hit hit<br>FIFO on the same string with 4 frames: 7 faults</pre><p>Check the FIFO row by hand. Pages 1, 2, 3 fill the frames. Page 4 evicts 1, so the next 1 faults and evicts 2, so the next 2 faults and evicts 3. Page 5 evicts 4. Then 1 and 2 are both still in memory and hit. Seven faults.</p><p>For the hand trace I write the full frame contents under every reference, not just F or hit. For FIFO I underline the oldest page, and for LRU I rewrite the frames in recency order each time. It is slower, but when you go wrong you can see where.</p><p>LRU also gets seven here, so LRU does not always beat FIFO on a given string. Optimal gets five, and that is your floor. It needs the future, so no real system can do it. The chapter calls it the offline lower bound, and if your hand trace beats it, you have miscounted.</p><h3>The anomaly</h3><p>The chapter says FIFO can show Belady’s anomaly, where more frames give more faults, and calls it a favourite trap. The lesson string above doesn’t show it: FIFO with 4 frames also gives 7. The textbook string is the same one extended by three pages, 1 2 3 4 1 2 5 1 2 3 4 5.</p><pre>belady = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]<br>print(&quot;Classic string:&quot;, belady)<br>for name, policy in ((&quot;FIFO&quot;, fifo), (&quot;LRU&quot;, lru)):<br>    for frames in (3, 4):<br>        print(f&quot;  {name}, {frames} frames: {policy(belady, frames)[0]} faults&quot;)</pre><pre>Classic string: [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]<br>  FIFO, 3 frames: 9 faults<br>  FIFO, 4 frames: 10 faults<br>  LRU, 3 frames: 10 faults<br>  LRU, 4 frames: 8 faults</pre><p>FIFO goes from 9 faults to 10 when it gets a fourth frame. The anomaly was described by Belady, Nelson and Shedler in “An anomaly in space-time characteristics of certain programs running in a paging machine”, <em>Communications of the ACM</em> 12(6), June 1969, pp. 349–353 (doi 10.1145/363011.363155).</p><p>LRU on the same string drops from 10 to 8, as you would expect. The reason is the stack property: the pages LRU holds with k frames are always a subset of what it holds with k+1 frames. FIFO keeps pages by arrival order, not by use, so it has no such property.</p><p>How common is this? I guessed “not very” and wanted a number, so I drew random strings of 12 references over pages 1 to 5, with a fixed seed so you can reproduce it, and compared 3 frames against 4.</p><pre>random.seed(2026)<br>trials, bad_fifo, bad_lru = 1_000_000, 0, 0<br>for _ in range(trials):<br>    refs = [random.randint(1, 5) for _ in range(12)]<br>    if fifo(refs, 4)[0] &gt; fifo(refs, 3)[0]:<br>        bad_fifo += 1<br>    if lru(refs, 4)[0] &gt; lru(refs, 3)[0]:<br>        bad_lru += 1<br>print(f&quot;{trials:,} random strings, 12 refs over pages 1-5, 3 frames vs 4:&quot;)<br>print(f&quot;  FIFO faulted more with 4 frames: {bad_fifo}&quot;)<br>print(f&quot;  LRU faulted more with 4 frames:  {bad_lru}&quot;)</pre><pre>1,000,000 random strings, 12 refs over pages 1-5, 3 frames vs 4:<br>  FIFO faulted more with 4 frames: 1<br>  LRU faulted more with 4 frames:  0</pre><p>One hit in a million. A first attempt with 100,000 strings found none, so I’d have written “never” if I’d stopped there. A single hit can’t pin down a rate, though, so I also counted exhaustively with a small C program: of all 5¹² = 244,140,625 strings of 12 references over five pages, FIFO faults more with 4 frames than with 3 in exactly 120 of them. That is about 1 in 2 million. It also explains why the textbook string looks hand-built. Someone had to go looking for it.</p><p>Don’t hunt for the anomaly in the trace. Look at the wording: of these three policies only FIFO can fault more with more frames, so a question asking which one can has its answer before you count anything. If the policy is LRU or Optimal, the anomaly can’t be the point.</p><p>The checker is also good for something duller. Take any previous-year question with a string and a frame count, run all three policies, and compare with your hand trace. Schoolabe’s GATE hub says its previous-year questions show questions and options only for now, and tells you to cross-check the official IIT answer key yourself. That is fair advice for any source, this one included.</p><p>CLOCK, the chapter’s fourth policy, is not covered here.</p><p><em>Written by the Schoolabe team, who build </em><a href="https://www.schoolabe.com/"><em>schoolabe.com</em></a><em>. The </em><a href="https://www.schoolabe.com/gate"><em>GATE CS section</em></a><em> lists free subject tutorials, topic quizzes and previous-year papers.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb86ab2a3be5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas Basics on a Real Dataset: A Hands-On Walkthrough with Palmer Penguins]]></title>
            <link>https://medium.com/@realdev9868/pandas-basics-on-a-real-dataset-a-hands-on-walkthrough-with-palmer-penguins-e69c03f9438e?source=rss-d5fa8071b756------2</link>
            <guid isPermaLink="false">https://medium.com/p/e69c03f9438e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Real Dev]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 16:28:25 GMT</pubDate>
            <atom:updated>2026-10-15T16:28:25.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Many pandas tutorials build a five-row DataFrame from a dictionary, so the data is already clean. Real data has missing values, text where you expected numbers, and questions you have to turn into code yourself.</p><p>In this post we’ll use a small but real dataset, <strong>Palmer Penguins</strong>, and go through a beginner’s workflow: load, inspect, clean, filter, create columns, group, and summarise. Every snippet below runs as written, and the outputs shown are the actual outputs.</p><h3>The dataset</h3><p>Palmer Penguins has measurements for 344 penguins of three species (Adelie, Chinstrap, Gentoo) from three islands in the Palmer Archipelago, Antarctica. The data was collected by Dr. Kristen Gorman and the Palmer Station LTER, and it’s released under CC0. It’s small enough to understand completely and messy enough to be realistic.</p><p>You’ll need Python 3 and pandas (pip install pandas). We&#39;ll read the CSV straight from a public URL.</p><h3>Step 1: Load and take a first look</h3><pre>import pandas as pd</pre><pre>url = &quot;https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv&quot;<br>df = pd.read_csv(url)</pre><pre>print(df.shape)<br>print(df.head())</pre><pre>(344, 7)<br>  species     island  bill_length_mm  ...  flipper_length_mm  body_mass_g     sex<br>0  Adelie  Torgersen            39.1  ...              181.0       3750.0    MALE<br>1  Adelie  Torgersen            39.5  ...              186.0       3800.0  FEMALE<br>2  Adelie  Torgersen            40.3  ...              195.0       3250.0  FEMALE<br>3  Adelie  Torgersen             NaN  ...                NaN          NaN     NaN<br>4  Adelie  Torgersen            36.7  ...              193.0       3450.0  FEMALE</pre><p>344 rows, 7 columns, and on row 3 we already have a fully missing record. Notice that flipper_length_mm and body_mass_g came in as floats (181.0). That&#39;s because pandas can&#39;t store NaN in a standard integer column, so a single missing value turns the whole column into floats.</p><h3>Step 2: Understand the columns</h3><pre>df.info()</pre><pre>RangeIndex: 344 entries, 0 to 343<br>Data columns (total 7 columns):<br> #   Column             Non-Null Count  Dtype<br>---  ------             --------------  -----<br> 0   species            344 non-null    str<br> 1   island             344 non-null    str<br> 2   bill_length_mm     342 non-null    float64<br> 3   bill_depth_mm      342 non-null    float64<br> 4   flipper_length_mm  342 non-null    float64<br> 5   body_mass_g        342 non-null    float64<br> 6   sex                333 non-null    str</pre><p>(On pandas 2.x, the text columns show up as object instead of str. Both mean the same thing here.)</p><p>info() is the first thing to run on any new dataset. It tells you the column types and how many non-null values each column has. We can already see that the four measurements are missing 2 values each, and sex is missing 11.</p><p>Then get a quick numeric summary:</p><pre>print(df.describe().round(1))</pre><pre>bill_length_mm  bill_depth_mm  flipper_length_mm  body_mass_g<br>count           342.0          342.0              342.0        342.0<br>mean             43.9           17.2              200.9       4201.8<br>std               5.5            2.0               14.1        802.0<br>min              32.1           13.1              172.0       2700.0<br>...<br>max              59.6           21.5              231.0       6300.0</pre><p>A body mass between 2.7 kg and 6.3 kg looks plausible for these species. Checking that the min and max make sense is a quick way to catch data-entry errors.</p><h3>Step 3: Find the missing values</h3><pre>print(df.isna().sum())</pre><pre>species               0<br>island                0<br>bill_length_mm        2<br>bill_depth_mm         2<br>flipper_length_mm     2<br>body_mass_g           2<br>sex                  11</pre><p>To see the actual rows:</p><pre>print(df[df.isna().any(axis=1)])</pre><p>This shows 11 rows. Two of them (rows 3 and 339) have no measurements at all. The other nine have measurements but no sex.</p><p>What you do with missing data depends on your question. If you’re studying body mass, rows with a recorded mass are still useful even when sex is unknown. So we drop rows only when the <em>measurements</em> are missing:</p><pre>measurements = [&quot;bill_length_mm&quot;, &quot;bill_depth_mm&quot;, &quot;flipper_length_mm&quot;, &quot;body_mass_g&quot;]<br>clean = df.dropna(subset=measurements).copy()<br>print(clean.shape)   # (342, 7)</pre><p>Two habits worth building early:</p><ul><li>Use subset= so you don&#39;t throw away rows you could have kept. A plain df.dropna() would drop all 11.</li><li>Use .copy() when you plan to add columns to a filtered DataFrame. It avoids the SettingWithCopyWarning you&#39;d otherwise see on older pandas versions, and it makes clear that clean is a separate table.</li></ul><h3>Step 4: Count categories</h3><pre>print(df[&quot;species&quot;].value_counts())</pre><pre>species<br>Adelie       152<br>Gentoo       124<br>Chinstrap     68</pre><p>Which species lives on which island? pd.crosstab gives you a frequency table in one line:</p><pre>print(pd.crosstab(df[&quot;species&quot;], df[&quot;island&quot;]))</pre><pre>island     Biscoe  Dream  Torgersen<br>species<br>Adelie         44     56         52<br>Chinstrap       0     68          0<br>Gentoo        124      0          0</pre><p>In this sample, Adelie penguins appear on all three islands, while Chinstrap appear only on Dream and Gentoo only on Biscoe. A table like this is useful later on, because a “difference between islands” could really be a difference between species.</p><h3>Step 5: Filter rows</h3><p>Boolean filtering is the pandas skill you’ll use most. Wrap each condition in parentheses and combine them with &amp; (and) or | (or). Don&#39;t use the Python keywords and/or here.</p><pre>heavy_gentoo = clean[(clean[&quot;species&quot;] == &quot;Gentoo&quot;) &amp; (clean[&quot;body_mass_g&quot;] &gt; 5500)]<br>print(len(heavy_gentoo))                                     # 28<br>print(heavy_gentoo[[&quot;island&quot;, &quot;sex&quot;, &quot;body_mass_g&quot;]].head())</pre><pre>island   sex  body_mass_g<br>221  Biscoe  MALE       5700.0<br>223  Biscoe  MALE       5700.0<br>231  Biscoe  MALE       5550.0<br>233  Biscoe  MALE       5850.0<br>235  Biscoe  MALE       5850.0</pre><p>query() does the same thing with a syntax that&#39;s often easier to read:</p><pre>print(clean.query(&quot;island == &#39;Dream&#39; and bill_length_mm &gt; 50&quot;).shape)   # (30, 7)</pre><h3>Step 6: Create new columns</h3><p>Arithmetic on columns works on the whole column at once, so no loop is needed:</p><pre>clean[&quot;body_mass_kg&quot;] = clean[&quot;body_mass_g&quot;] / 1000<br>clean[&quot;bill_ratio&quot;] = (clean[&quot;bill_length_mm&quot;] / clean[&quot;bill_depth_mm&quot;]).round(2)</pre><pre>print(clean[[&quot;species&quot;, &quot;body_mass_kg&quot;, &quot;bill_ratio&quot;]].head(3))</pre><pre>species  body_mass_kg  bill_ratio<br>0  Adelie          3.75        2.09<br>1  Adelie          3.80        2.27<br>2  Adelie          3.25        2.24</pre><h3>Step 7: Group and summarise</h3><p>This is where pandas really helps. The question “What’s the average body mass of each species?” becomes:</p><pre>print(clean.groupby(&quot;species&quot;)[&quot;body_mass_g&quot;].mean().round(0))</pre><pre>species<br>Adelie       3701.0<br>Chinstrap    3733.0<br>Gentoo       5076.0</pre><p>For several statistics at once, use <strong>named aggregation</strong>. It gives you clean column names, which helps when you export the result:</p><pre>summary = (<br>    clean.groupby(&quot;species&quot;)<br>         .agg(count=(&quot;body_mass_g&quot;, &quot;size&quot;),<br>              avg_mass_g=(&quot;body_mass_g&quot;, &quot;mean&quot;),<br>              avg_flipper_mm=(&quot;flipper_length_mm&quot;, &quot;mean&quot;),<br>              avg_bill_ratio=(&quot;bill_ratio&quot;, &quot;mean&quot;))<br>         .round(1)<br>         .sort_values(&quot;avg_mass_g&quot;, ascending=False)<br>)<br>print(summary)</pre><pre>count  avg_mass_g  avg_flipper_mm  avg_bill_ratio<br>species<br>Gentoo       123      5076.0           217.2             3.2<br>Chinstrap     68      3733.1           195.8             2.7<br>Adelie       151      3700.7           190.0             2.1</pre><p>In this data, Gentoo penguins are clearly the heaviest and have the longest flippers. Their bills are also long relative to their depth, which is why their bill ratio is the highest.</p><h3>Step 8: Two dimensions with a pivot table</h3><p>Average body mass by species <strong>and</strong> sex. Here we drop rows where sex is missing, because they can’t go in either column:</p><pre>by_sex = (<br>    clean.dropna(subset=[&quot;sex&quot;])<br>         .pivot_table(index=&quot;species&quot;, columns=&quot;sex&quot;,<br>                      values=&quot;body_mass_g&quot;, aggfunc=&quot;mean&quot;)<br>         .round(0)<br>)<br>print(by_sex)</pre><pre>sex        FEMALE    MALE<br>species<br>Adelie     3369.0  4043.0<br>Chinstrap  3527.0  3939.0<br>Gentoo     4680.0  5485.0</pre><p>In every species in this sample, males are heavier on average. You worked that out yourself from raw data in about 30 lines of code.</p><h3>Step 9: Save your work</h3><pre>summary.to_csv(&quot;penguin_summary.csv&quot;)</pre><h3>Cheat sheet</h3><ul><li><strong>Load CSV</strong>: pd.read_csv(path_or_url)</li><li><strong>Size, types, nulls</strong>: df.shape, df.info(), df.isna().sum()</li><li><strong>Numeric summary</strong>: df.describe()</li><li><strong>Category counts</strong>: df[&quot;col&quot;].value_counts()</li><li><strong>Filter rows</strong>: df[(cond1) &amp; (cond2)] or df.query(&quot;...&quot;)</li><li><strong>Drop missing (selectively)</strong>: df.dropna(subset=[...])</li><li><strong>New column</strong>: df[&quot;new&quot;] = df[&quot;a&quot;] / df[&quot;b&quot;]</li><li><strong>Group stats</strong>: df.groupby(&quot;k&quot;).agg(name=(&quot;col&quot;, &quot;mean&quot;))</li><li><strong>2-D summary</strong>: df.pivot_table(index=, columns=, values=, aggfunc=)</li></ul><h3>Try it in the browser</h3><p>If you’d rather not set anything up locally, our <a href="https://www.schoolabe.com/data-analysis-lab">Data Analysis Lab</a> has notebook-style pages for NumPy, Pandas and Matplotlib that run in the browser, using the same Palmer Penguins data. The <a href="https://www.schoolabe.com/data-analysis-lab/exercise-pandas-species-mass">mean body mass by species</a> exercise is a good way to check that Step 7 stuck.</p><p><strong>Your next challenge:</strong> find the island with the highest average flipper length <em>for Adelie penguins only</em> (they’re the one species found on all three islands), and check whether the sex split looks similar on each island.</p><p>— Schoolabe team</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e69c03f9438e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Joins Explained with One Tiny Dataset (Plus 5 Interview Questions)]]></title>
            <link>https://medium.com/@realdev9868/sql-joins-explained-with-one-tiny-dataset-plus-5-interview-questions-9c0cfe711cf3?source=rss-d5fa8071b756------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c0cfe711cf3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Real Dev]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 16:14:11 GMT</pubDate>
            <atom:updated>2026-10-19T03:23:50.360Z</atom:updated>
            <content:encoded><![CDATA[<p>Most join tutorials show you a Venn diagram and move on. Then an interviewer asks, &quot;Why did your row count go up after the join?&quot; or &quot;Why did your LEFT JOIN behave like an INNER JOIN?&quot;, and the diagram doesn&#39;t help.</p><p>In this post we&#39;ll use <strong>one small dataset</strong> (two tables, ten rows in total) and run every join type on it, so you can see exactly which rows survive. Then we&#39;ll work through five interview-style questions that test whether you really understand joins, not just the syntax.</p><p>Everything below runs on SQLite 3.39 or newer (and on PostgreSQL). If you&#39;re on MySQL, everything works except FULL OUTER JOIN, which MySQL doesn&#39;t support. We show the usual workaround below.</p><h3>The setup</h3><p>Copy this into any SQL editor:</p><pre>CREATE TABLE departments (<br>  id   INTEGER PRIMARY KEY,<br>  name TEXT NOT NULL,<br>  city TEXT<br>);<br><br>CREATE TABLE employees (<br>  id         INTEGER PRIMARY KEY,<br>  name       TEXT NOT NULL,<br>  dept_id    INTEGER REFERENCES departments(id),<br>  manager_id INTEGER REFERENCES employees(id),<br>  salary     INTEGER<br>);<br><br>INSERT INTO departments VALUES<br>  (1, &#39;Engineering&#39;, &#39;Bengaluru&#39;),<br>  (2, &#39;Sales&#39;,       &#39;Mumbai&#39;),<br>  (3, &#39;HR&#39;,          &#39;Pune&#39;),<br>  (4, &#39;Legal&#39;,       &#39;Delhi&#39;);<br><br>INSERT INTO employees VALUES<br>  (1, &#39;Asha&#39;,  1, NULL, 150000),<br>  (2, &#39;Ravi&#39;,  1, 1,     90000),<br>  (3, &#39;Priya&#39;, 2, 1,     80000),<br>  (4, &#39;Karan&#39;, 2, 3,     60000),<br>  (5, &#39;Neha&#39;,  NULL, 1,  70000),<br>  (6, &#39;Arjun&#39;, 3, 1,     65000);</pre><p>Two details are there on purpose, because they&#39;re what make joins interesting:</p><ul><li><strong>Neha</strong> has no department (dept_id is NULL).</li><li><strong>Legal</strong> has no employees.</li></ul><p>Keep an eye on those two rows. The difference between join types comes down to what happens to them.</p><h3>INNER JOIN: only matching rows</h3><pre>SELECT e.name, d.name AS dept<br>FROM employees e<br>INNER JOIN departments d ON e.dept_id = d.id;</pre><pre>name   dept<br>-----  -----------<br>Asha   Engineering<br>Ravi   Engineering<br>Priya  Sales<br>Karan  Sales<br>Arjun  HR</pre><p>Neha is gone (she matches no department) and so is Legal (it matches no employee). An inner join keeps a row only when the ON condition is true for both sides. JOIN on its own means INNER JOIN.</p><h3>LEFT JOIN: keep everything from the left table</h3><pre>SELECT e.name, d.name AS dept<br>FROM employees e<br>LEFT JOIN departments d ON e.dept_id = d.id;</pre><p>You get the same five rows plus Neha | NULL. Every employee shows up. Where there&#39;s no match, the right-hand columns are filled with NULL. Legal still doesn&#39;t appear, because departments is the right table here.</p><h3>RIGHT JOIN: the mirror image</h3><pre>SELECT e.name, d.name AS dept<br>FROM employees e<br>RIGHT JOIN departments d ON e.dept_id = d.id;</pre><p>Now Legal appears as NULL | Legal, and Neha disappears. In practice most people just swap the table order and write a LEFT JOIN, because it reads more naturally.</p><h3>FULL OUTER JOIN: keep everything from both</h3><pre>SELECT e.name, d.name AS dept<br>FROM employees e<br>FULL OUTER JOIN departments d ON e.dept_id = d.id;</pre><p>Seven rows: the five matches, Neha | NULL, and NULL | Legal. On MySQL you can get the same result with a LEFT JOIN ... UNION ... RIGHT JOIN of the same two tables.</p><h3>CROSS JOIN: every combination</h3><pre>SELECT COUNT(*) AS combos<br>FROM employees CROSS JOIN departments;</pre><p>That returns 24 (6 employees × 4 departments). You rarely want this on purpose. Usually it shows up by accident when someone forgets the ON condition. If your result ever has &quot;rows × rows&quot; in it, check your join condition first.</p><blockquote><strong><em>Note:</em></strong><em> SQL doesn&#39;t promise any row order unless you write </em><em>ORDER BY. Your rows may come back in a different order from the tables above. That&#39;s fine.</em></blockquote><h3>5 interview questions on joins</h3><p>These are the kinds of questions that separate &quot;I&#39;ve used joins&quot; from &quot;I understand joins.&quot; Try each one yourself before you read the answer.</p><h3>1. Find departments that have no employees</h3><pre>SELECT d.name<br>FROM departments d<br>LEFT JOIN employees e ON e.dept_id = d.id<br>WHERE e.id IS NULL;</pre><p>Result: Legal. This is the <strong>anti-join</strong> pattern: LEFT JOIN, then keep only the rows where the right side didn&#39;t match. Check a column that can never be NULL in a real match, such as the primary key e.id. NOT EXISTS is an equally good answer, and it&#39;s worth mentioning both.</p><h3>2. List each employee with their manager&#39;s name</h3><pre>SELECT e.name AS employee, m.name AS manager<br>FROM employees e<br>LEFT JOIN employees m ON e.manager_id = m.id;</pre><p>This is a <strong>self join</strong>: the same table, under two aliases. Interviewers like to ask why it&#39;s a LEFT JOIN. The answer: Asha has no manager, and with an INNER JOIN she would disappear from the list.</p><h3>3. Why did my LEFT JOIN turn into an INNER JOIN?</h3><p>Compare these two queries:</p><pre>-- Version A: filter in WHERE<br>SELECT d.name, e.name<br>FROM departments d<br>LEFT JOIN employees e ON e.dept_id = d.id<br>WHERE e.salary &gt; 70000;<br><br>-- Version B: filter in ON<br>SELECT d.name, e.name<br>FROM departments d<br>LEFT JOIN employees e ON e.dept_id = d.id AND e.salary &gt; 70000;</pre><p>Version A returns 3 rows (Engineering twice, Sales once). Version B returns 5: the same 3, plus HR | NULL and Legal | NULL.</p><p>Why? WHERE runs <strong>after</strong> the join. The unmatched rows have e.salary = NULL, and NULL &gt; 70000 is not true, so WHERE throws them away. Your LEFT JOIN quietly becomes an inner join. If the question is &quot;show every department, and any well-paid employees in it,&quot; the filter on the right table belongs in ON.</p><h3>4. Count employees per department, including empty ones</h3><pre>SELECT d.name, COUNT(*) AS wrong, COUNT(e.id) AS headcount<br>FROM departments d<br>LEFT JOIN employees e ON e.dept_id = d.id<br>GROUP BY d.id, d.name;</pre><pre>name         wrong  headcount<br>-----------  -----  ---------<br>Engineering  2      2<br>Sales        2      2<br>HR           1      1<br>Legal        1      0</pre><p>COUNT(*) counts rows, and the LEFT JOIN produced one row for Legal (full of NULLs). COUNT(e.id) counts only non-NULL values, which gives the right headcount of 0. Mixing these two up is a classic way to fail this question.</p><p>The same idea explains the &quot;why did my row count go up?&quot; question. In a one-to-many join, each department row is repeated once for every matching employee. That&#39;s correct behaviour. Just remember it before you SUM a column from the &quot;one&quot; side.</p><h3>5. Highest-paid employee in each department</h3><p>Version with a correlated subquery:</p><pre>SELECT d.name AS dept, e.name, e.salary<br>FROM employees e<br>JOIN departments d ON e.dept_id = d.id<br>WHERE e.salary = (<br>  SELECT MAX(e2.salary)<br>  FROM employees e2<br>  WHERE e2.dept_id = e.dept_id<br>);</pre><p>Version with a window function:</p><pre>SELECT dept, name, salary<br>FROM (<br>  SELECT d.name AS dept, e.name, e.salary,<br>         RANK() OVER (PARTITION BY e.dept_id ORDER BY e.salary DESC) AS rnk<br>  FROM employees e<br>  JOIN departments d ON e.dept_id = d.id<br>)<br>WHERE rnk = 1;</pre><p>Both return Asha (Engineering), Priya (Sales) and Arjun (HR). A good follow-up to bring up yourself is ties: RANK() keeps every employee tied for the top salary, while ROW_NUMBER() would pick exactly one of them.</p><h3>A quick mental checklist</h3><p>Before you run any join, ask yourself:</p><ol><li><strong>Which rows must not disappear?</strong> That table goes on the left of a LEFT JOIN.</li><li><strong>Is this one-to-one or one-to-many?</strong> If it&#39;s one-to-many, expect repeated rows and be careful with aggregates.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c0cfe711cf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>