<?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 Vedant Rathore on Medium]]></title>
        <description><![CDATA[Stories by Vedant Rathore on Medium]]></description>
        <link>https://medium.com/@vedantrathore627?source=rss-ad88990b5c59------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QoVg8-hzlF3HarGi</url>
            <title>Stories by Vedant Rathore on Medium</title>
            <link>https://medium.com/@vedantrathore627?source=rss-ad88990b5c59------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:15:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vedantrathore627/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[Multithreading in Java — Part 1: From Program to Threads]]></title>
            <link>https://medium.com/@vedantrathore627/multithreading-in-java-part-1-from-program-to-threads-612d6cf1d211?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/612d6cf1d211</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[threading-in-java]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 10:12:53 GMT</pubDate>
            <atom:updated>2026-10-11T10:12:53.428Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Let’s understand what actually happens when we run a Java program, how the JVM manages memory, and how the CPU executes threads.</em></p><p>Multithreading often feels complicated because we learn too many terms at once: processes, threads, stacks, heaps, concurrency, parallelism, and context switching.</p><p>Let’s understand them in the order they actually fit together.</p><p>Imagine clicking on Spotify. What happens inside your computer? Where was Spotify before you clicked it? Who starts it? And where does the CPU come into the picture?</p><p>Let’s start from the basics.</p><h3>1. Program: A Set of Instructions</h3><p>A program is simply a set of instructions written to perform a task.</p><p>For example, Spotify, Chrome, or even a simple Java file.</p><pre>public class Student {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello World&quot;);<br>    }<br>}</pre><p>When you save this code, Student.java is stored on your disk (SSD or HDD).</p><p><strong>At this point, the file exists, but the code isn’t executing.</strong></p><h3>Diagram 1 — Program on disk</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhbcYqH4oaNW4mxP3emR9A.png" /></figure><p>The important point is that a program stored on disk is just instructions waiting to be executed.</p><h3>2. Process: When a Program Starts Running</h3><p>Now, suppose you click on Spotify.</p><p>Who starts it?</p><p><strong>The operating system (OS).</strong></p><p>The OS creates a process and sets up the memory and resources needed to run the application.</p><p>A process is a running instance of a program.</p><h3>Diagram 2 — From program to process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTje1HXpOtxqb8heAi95_Q.png" /></figure><p>The OS manages the process’s memory and resources. The program’s code and other required data are made available to the process as needed.</p><p>One technical detail: the OS doesn’t necessarily load the entire program into physical RAM at once. Modern systems use virtual memory and load or map pages as required.</p><p>For now, remember:</p><ul><li>Program: Instructions stored on disk.</li><li>Process: A running instance of a program.</li><li>OS: Creates processes and manages their resources.</li></ul><p>Now comes the interesting part.</p><h3>3. Thread: Where Things Get Interesting</h3><p>Imagine your application needs to download a file, process it, and save the result.</p><p>We can organize this work using multiple threads so different tasks can make progress independently.</p><p>A thread is an independent sequence of execution inside a process.</p><p>Let’s create two worker threads in Java.</p><pre>public class Main {<br>    public static void main(String[] args) {</pre><pre>        Thread t1 = new Thread(() -&gt;<br>            System.out.println(&quot;Downloading file&quot;)<br>        );</pre><pre>        Thread t2 = new Thread(() -&gt;<br>            System.out.println(&quot;Processing file&quot;)<br>        );</pre><pre>        t1.start();<br>        t2.start();<br>    }<br>}</pre><p>Here, we create two threads and start them.</p><p>Notice that we use start(), not run(). Calling start() allows the JVM to initiate a new thread of execution. We&#39;ll explore this difference in the next article.</p><p>The output order isn’t guaranteed. Either thread may print first.</p><h3>Diagram 3 — One process, multiple threads</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQOyVuk4nS36jkT1bCecog.png" /></figure><p>Each thread has its own execution state, but threads within the same process can share memory.</p><p>Let’s understand how.</p><h3>4. Where Does the JVM Come In?</h3><p>When you run a Java application, the OS starts a process for it, and the Java launcher starts the JVM inside that process.</p><p>The JVM provides the environment needed to run Java code.</p><p>Our execution flow now looks like this:</p><p><strong>Program → OS creates process → JVM starts → Main thread executes Java code.</strong></p><p>The JVM starts executing the main() method using the main thread. When we create additional threads, the JVM works with the underlying threading system to execute them.</p><p>For traditional Java platform threads, each Java thread generally corresponds to an operating-system thread.</p><h3>Diagram 4 — JVM inside a Java process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*Awa98kK9Q-N0at1qL6tPgw.png" /></figure><p>The OS and JVM have different responsibilities:</p><ul><li>OS: Process management, system resources, and thread scheduling.</li><li>JVM: Java execution, class loading, memory management, and garbage collection.</li><li>CPU: Executes machine instructions.</li></ul><p>Now let’s look inside the JVM.</p><h3>5. JVM Memory: Heap, Method Area, Stack and PC</h3><p>This is one of the most important parts of understanding multithreading.</p><p>Suppose our Java process has three threads. Does each thread get completely separate memory?</p><p>No. Some memory is shared, while some is private to each thread.</p><h3>Diagram 5 — JVM memory structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*F6mndpJHxL48zxu0vwQhlw.png" /></figure><ul><li><strong>Shared across threads</strong></li><li>Heap: Objects and arrays.</li><li>Method Area: Class-related runtime information.</li><li><strong>Private to each thread</strong></li><li>Stack: Method-call frames and local variables.</li><li>Program Counter (PC): Tracks the next JVM instruction to execute.</li></ul><p>The diagram should show three threads — Main, Worker 1, and Worker 2 — each with its own Stack and PC, all connected to the same Heap and Method Area.</p><p>Let’s understand each part with Java code.</p><h3>Heap: Where objects live</h3><pre>Student student = new Student();</pre><p>The new Student() expression creates a Student object on the heap in the usual Java execution model.</p><p>Multiple threads can access the same object if they have references to it.</p><p>This is why shared objects become important when learning thread safety.</p><h3>Stack: Each thread has its own</h3><pre>void calculate() {<br>    int number = 10;<br>    int result = number * 2;<br>}</pre><p>When a thread executes calculate(), its stack contains a frame for that method invocation.</p><p>If another thread executes the same method, it gets its own invocation frame and local variables.</p><p>Each thread has its own stack.</p><h3>Method Area: Class-related information</h3><p>The Method Area is a JVM concept that holds class-related runtime structures.</p><p>In the HotSpot JVM, class metadata is commonly stored in native memory called Metaspace.</p><p>You don’t need to go deeper into its implementation right now. Just remember that the Method Area is shared runtime information, unlike each thread’s private stack.</p><h3>Program Counter (PC)</h3><p>Each JVM thread has its own PC register, which tracks the next JVM instruction to execute.</p><p>This is part of how the JVM maintains the execution state of individual threads.</p><p><strong>Quick memory rule: Heap and Method Area are shared; Stack and PC are thread-specific.</strong></p><h3>6. How Does the CPU Execute Threads?</h3><p>Now we have a Java process containing multiple threads.</p><p>Who decides which thread executes?</p><p>For traditional platform threads, the OS scheduler decides which runnable threads get CPU time.</p><p>The CPU executes the actual machine instructions.</p><p>Let’s consider two scenarios.</p><h3>Scenario A: One CPU core</h3><p>Suppose three threads are ready to run, but only one CPU core is available.</p><p>Can all three execute instructions simultaneously on that core?</p><p>No.</p><p>The core executes one instruction stream at a time. The OS can switch between threads, giving each an opportunity to execute.</p><h3>Diagram 6 — Context switching on one core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dKhEEZJNwX_ENZ4FpZ6_g.png" /></figure><p>This is called context switching.</p><p>The system preserves the outgoing thread’s execution state and restores the incoming thread’s state.</p><p>Even though only one thread executes at a time on that core, multiple threads can make progress over the same period.</p><p>This is concurrency.</p><h3>Scenario B: Two CPU cores</h3><p>Now suppose two CPU cores are available.</p><p>Core 1 can execute Thread 1 while Core 2 executes Thread 2.</p><p>Both threads can execute instructions at the same instant.</p><h3>Diagram 7 — True parallelism</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*XZHkxZaqoz5FrUVq_IHtfA.png" /></figure><p>This is parallelism.</p><p>Remember:</p><ul><li>One core: Threads can take turns, enabling concurrency.</li><li>Multiple cores: Different threads can execute simultaneously, enabling parallelism.</li></ul><p>A multi-core system can do both.</p><h3>7. Multitasking vs. Multithreading</h3><p>Let’s finish with one simple distinction.</p><p><strong>Multitasking:</strong> Running multiple applications, such as Chrome, Spotify, and IntelliJ IDEA.</p><p><strong>Multithreading:</strong> Using multiple threads inside one process to perform different tasks.</p><p>MultitaskingMultithreadingMultiple tasks or applicationsMultiple threads within a processExample: Chrome and SpotifyExample: Main and worker threads in JavaProcesses generally have separate virtual address spacesThreads can share the same process memoryOS manages processes and schedules their threadsApplication uses threads to organize its work</p><p>Both can happen at the same time. Your computer can run multiple applications, and each application can use multiple threads.</p><h3>8. Quick Revision: Things to Remember</h3><ol><li>Program = Instructions stored on disk.</li><li>Process = A running instance of a program.</li><li>OS = Creates processes and manages resources and scheduling.</li><li>Thread = An independent sequence of execution inside a process.</li><li>JVM = Runs Java applications and manages Java runtime facilities.</li><li>Heap = Where Java objects and arrays are allocated.</li><li>Method Area = Shared class-related runtime information.</li><li>Stack = Each thread has its own stack.</li><li>PC = Each JVM thread has its own program counter.</li><li>Context switching = Switching execution between threads.</li><li>Concurrency = Multiple tasks make progress over overlapping periods.</li><li>Parallelism = Multiple tasks execute simultaneously.</li><li>Multitasking = Multiple tasks or applications.</li><li>Multithreading = Multiple threads within a process.</li></ol><p>The entire flow can be remembered in one line:</p><p><strong>Program → Process → JVM → Threads → CPU execution</strong></p><p>With one core, threads can take turns. With multiple cores, different threads can execute simultaneously.</p><p>Now we have the foundation.</p><p>In Part 2, we’ll write more Java code, create threads using Thread and Runnable, and understand why start() and run() behave differently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=612d6cf1d211" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles, Finally Explained Simply]]></title>
            <link>https://medium.com/@vedantrathore627/solid-principles-finally-explained-simply-cc10167ab6e7?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc10167ab6e7</guid>
            <category><![CDATA[sde-interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[lld]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 16:01:52 GMT</pubDate>
            <atom:updated>2026-10-04T16:01:52.041Z</atom:updated>
            <content:encoded><![CDATA[<p>I used to think SOLID was five separate rules that I had to memorize.</p><p>SRP.</p><p>OCP.</p><p>LSP.</p><p>ISP.</p><p>DIP.</p><p>I could remember the full forms, but when someone asked me:</p><blockquote><em>“Why do we actually need SOLID?”</em></blockquote><p>I wasn’t always able to give a simple answer.</p><p>The more I studied it, the more I realized something:</p><p><strong>SOLID is not really about memorizing five definitions.</strong></p><p>It is mostly about one thing:</p><blockquote><strong><em>How do we design code so that when the system changes, the change stays where it belongs?</em></strong></blockquote><p>In this article, I will explain SOLID using <strong>one example throughout</strong> — an OrderService in an e-commerce application.</p><p>No Animal, Bird, Vehicle, or random examples.</p><p>Just one realistic engineering example.</p><h3>First: What problem is SOLID trying to solve?</h3><p>Imagine we start with this:</p><pre>class OrderService {</pre><pre>    void placeOrder(Order order) {</pre><pre>        // validate order</pre><pre>        // calculate total</pre><pre>        // save order to database</pre><pre>        // generate invoice PDF</pre><pre>        // send email<br>    }<br>}</pre><p>At first glance, this might look completely fine.</p><p>The order is placed, so why not keep everything inside OrderService?</p><p>The problem appears when the application grows.</p><p>Now we get requirements like:</p><ul><li>We need SMS notifications.</li><li>We need push notifications.</li><li>PDF format needs to change.</li><li>Database changes from MySQL to something else.</li><li>Email provider changes.</li><li>We need better testing.</li><li>We need different notification strategies.</li><li>We need to extend the system without constantly modifying existing code.</li></ul><p>Suddenly, one small class is connected to many different things.</p><p>This is where SOLID starts becoming useful.</p><h3>1. SRP — Single Responsibility Principle</h3><p>The simplest way to remember SRP is:</p><blockquote><strong><em>A class should have one reason to change.</em></strong></blockquote><p>Notice that I didn’t say:</p><blockquote><em>“A class should have only one method.”</em></blockquote><p>That’s a very common misunderstanding.</p><p>For example, this is perfectly fine:</p><pre>class OrderService {</pre><pre>    void validateOrder() {<br>    }</pre><pre>    void calculateOrderTotal() {<br>    }</pre><pre>    void placeOrder() {<br>    }<br>}</pre><p>All three methods are related to the responsibility of handling an order.</p><p>But imagine this:</p><pre>class OrderService {</pre><pre>    void validateOrder() {<br>    }</pre><pre>    void calculateOrderTotal() {<br>    }</pre><pre>    void saveToDatabase() {<br>    }</pre><pre>    void generatePDF() {<br>    }</pre><pre>    void sendEmail() {<br>    }<br>}</pre><p>Now the class has multiple reasons to change.</p><p>Think about it.</p><p>If the PDF library changes:</p><pre>OrderService changes</pre><p>If the database changes:</p><pre>OrderService changes</pre><p>If the email provider changes:</p><pre>OrderService changes</pre><p>If order calculation changes:</p><pre>OrderService changes</pre><p>That’s the problem.</p><p>We can separate the responsibilities:</p><pre>OrderService<br>    → order-related logic</pre><pre>OrderRepository<br>    → database-related logic</pre><pre>InvoiceGenerator<br>    → PDF-related logic</pre><pre>NotificationService<br>    → notification-related logic</pre><p>Now a PDF change doesn’t require us to touch OrderService.</p><p>A database change doesn’t require us to touch OrderService.</p><p>This is SRP.</p><h3>The simplest mental model</h3><blockquote><strong><em>Keep things that change for different reasons in different places.</em></strong></blockquote><p>SRP is mostly about <strong>clear separation and cohesion</strong>.</p><h3>2. OCP — Open/Closed Principle</h3><p>OCP says:</p><blockquote><strong><em>Software should be open for extension but closed for modification.</em></strong></blockquote><p>This sounds complicated, but the basic idea is simple.</p><p>Suppose today our application only supports email notifications.</p><pre>class Notification {</pre><pre>    void email() {<br>        // email logic<br>    }<br>}</pre><p>Tomorrow, a new requirement arrives:</p><blockquote><em>“We also need SMS.”</em></blockquote><p>A naive solution might be:</p><pre>class Notification {</pre><pre>    void email() {<br>        // email logic<br>    }</pre><pre>    void sms() {<br>        // SMS logic<br>    }<br>}</pre><p>We opened an existing class and modified it to add new behavior.</p><p>Imagine this happening repeatedly:</p><pre>Email<br>↓<br>Add SMS<br>↓<br>Modify Notification</pre><pre>Add Push<br>↓<br>Modify Notification</pre><pre>Add WhatsApp<br>↓<br>Modify Notification</pre><pre>Add Slack<br>↓<br>Modify Notification</pre><p>The same file keeps growing.</p><p>That creates several problems:</p><ul><li>readability gets worse</li><li>the class becomes harder to maintain</li><li>chages can introduce regressions</li><li>testing becomes harder</li><li>unrelated notification logic starts accumulating in one place</li></ul><p>Instead, we can create an extension point:</p><pre>interface Notification {</pre><pre>    void send();<br>}</pre><p>Then:</p><pre>class EmailNotification implements Notification {</pre><pre>    public void send() {<br>        // email logic<br>    }<br>}</pre><p>Later:</p><pre>class SMSNotification implements Notification {</pre><pre>    public void send() {<br>        // SMS logic<br>    }<br>}</pre><p>And later:</p><pre>class PushNotification implements Notification {</pre><pre>    public void send() {<br>        // push logic<br>    }<br>}</pre><p>Now when SMS is introduced, we add a new class instead of modifying the existing email implementation.</p><p>That’s the important idea behind OCP.</p><h3>Don’t misunderstand OCP</h3><p>OCP does <strong>not</strong> mean:</p><blockquote><em>“I must predict every possible future requirement.”</em></blockquote><p>That’s impossible.</p><p>You shouldn’t create 50 interfaces just because maybe 50 implementations might exist someday.</p><p>Instead:</p><blockquote><strong><em>When you have a known or likely area of variation, design it so new variations can be added without repeatedly modifying stable code.</em></strong></blockquote><p>Also, OCP is mainly useful when we talk about <strong>new requirements or extensions</strong>.</p><p>For example:</p><blockquote><em>“We now need SMS.”</em></blockquote><p>That’s a classic OCP situation.</p><p>If an existing email implementation internally changes from one email provider to another and OrderService has to change, the first thing I would think about is <strong>coupling and DIP</strong>.</p><p>We should not force every problem into OCP.</p><h3>3. LSP — Liskov Substitution Principle</h3><p>LSP is probably the principle that sounds the most complicated when you first read its formal definition.</p><p>The formal version is roughly:</p><blockquote><strong><em>A child type should be usable wherever its parent type is expected without breaking the expected behavior of the program.</em></strong></blockquote><p>Let’s use our notification example.</p><p>We have:</p><pre>interface Notification {</pre><pre>    void send();<br>}</pre><p>And:</p><pre>EmailNotification<br>SMSNotification<br>PushNotification</pre><p>Now imagine our client has:</p><pre>Notification notification;</pre><pre>notification.send();</pre><p>The client doesn’t care which implementation it received.</p><p>It trusts the contract.</p><p>That’s the important word:</p><blockquote><strong><em>Trust.</em></strong></blockquote><p>The client is essentially saying:</p><blockquote><em>“You told me this object is a </em><em>Notification. Fine. I trust that calling </em><em>send() will behave like a notification.&quot;</em></blockquote><p>Now imagine this:</p><pre>class SMSNotification implements Notification {</pre><pre>    public void send() {<br>        throw new UnsupportedOperationException();<br>    }<br>}</pre><p>Technically, it implements Notification.</p><p>But practically, something is wrong.</p><p>The client expected:</p><pre>notification.send();</pre><p>to work.</p><p>Instead, it gets an exception.</p><p>The abstraction made a promise, but the implementation didn’t keep that promise.</p><p>That’s an LSP problem.</p><h3>A simple way to remember LSP</h3><blockquote><strong><em>LSP asks: “Can I trust every implementation of this abstraction to behave as promised?”</em></strong></blockquote><p>Or even simpler:</p><blockquote><strong><em>The abstraction should not surprise its client.</em></strong></blockquote><p>The client should not need to know:</p><pre>if (notification instanceof SMSNotification) {<br>    // special handling<br>}</pre><p>If every implementation requires special treatment, our abstraction is probably not doing its job properly.</p><h3>4. ISP — Interface Segregation Principle</h3><p>ISP is actually quite simple.</p><blockquote><strong><em>Don’t force a class to depend on methods it doesn’t need.</em></strong></blockquote><p>Suppose we create:</p><pre>interface Notification {</pre><pre>    void send();</pre><pre>    void schedule();</pre><pre>    void cancel();</pre><pre>    void trackDelivery();</pre><pre>    void retry();<br>}</pre><p>Now imagine SMSNotification doesn&#39;t support scheduling.</p><p>We might end up with:</p><pre>class SMSNotification implements Notification {</pre><pre>    public void send() {<br>        // SMS<br>    }</pre><pre>    public void schedule() {<br>        throw new UnsupportedOperationException();<br>    }</pre><pre>    public void cancel() {<br>        throw new UnsupportedOperationException();<br>    }</pre><pre>    ...<br>}</pre><p>That’s a smell.</p><p>Our interface has become too large.</p><p>Instead, we can separate the capabilities:</p><pre>interface Notification {<br>    void send();<br>}</pre><pre>interface Schedulable {<br>    void schedule();<br>}</pre><pre>interface Cancellable {<br>    void cancel();<br>}</pre><p>Now a class only implements what it actually needs.</p><h3>Mental model</h3><blockquote><strong><em>Don’t make someone depend on things they don’t need.</em></strong></blockquote><p>That’s ISP.</p><h3>5. DIP — Dependency Inversion Principle</h3><p>This is the one I personally find the most important to understand deeply.</p><p>DIP is often explained as:</p><blockquote><em>“Depend on abstractions, not concrete implementations.”</em></blockquote><p>That’s correct, but let’s understand <strong>why</strong>.</p><h3>First, look at tight coupling</h3><p>Suppose we write:</p><pre>class OrderService {</pre><pre>    EmailService emailService = new EmailService();</pre><pre>    void placeOrder(Order order) {</pre><pre>        // order logic</pre><pre>        emailService.sendEmail();<br>    }<br>}</pre><p>What’s happening here?</p><p>OrderService directly knows about EmailService.</p><p>It knows:</p><ul><li>which concrete class to use</li><li>how to create it</li><li>which method to call</li><li>potentially details about how that service works</li></ul><p>This is <strong>tight coupling</strong>.</p><p>We can visualize it:</p><pre>OrderService<br>     |<br>     ↓<br>EmailService</pre><p>OrderService is strongly connected to EmailService.</p><h3>Why is tight coupling a problem?</h3><p>Imagine the email implementation changes.</p><p>Maybe we change the email provider.</p><p>Maybe the API changes.</p><p>Maybe we want to replace email with another notification system.</p><p>Because OrderService directly depends on the concrete implementation, changes can ripple into OrderService.</p><p>That’s the <strong>ripple effect</strong>.</p><pre>EmailService changes<br>        ↓<br>OrderService may need changes<br>        ↓<br>Tests may need changes<br>        ↓<br>Other dependent code may need changes</pre><p>The more tightly coupled the system is, the more likely a change in one place spreads into other places.</p><h3>Loose coupling</h3><p>Instead of this:</p><pre>OrderService<br>     |<br>     ↓<br>EmailService</pre><p>we introduce an abstraction:</p><pre>interface Notification {</pre><pre>    void send();<br>}</pre><p>Then:</p><pre>class EmailNotification implements Notification {</pre><pre>    public void send() {<br>        // email<br>    }<br>}</pre><pre>class SMSNotification implements Notification {</pre><pre>    public void send() {<br>        // SMS<br>    }<br>}</pre><p>And our OrderService becomes:</p><pre>class OrderService {</pre><pre>    private final Notification notification;</pre><pre>    OrderService(Notification notification) {<br>        this.notification = notification;<br>    }</pre><pre>    void placeOrder(Order order) {</pre><pre>        // order logic</pre><pre>        notification.send();<br>    }<br>}</pre><p>Now look at the relationship:</p><pre>Notification<br>              /     |      \<br>             /      |       \<br>         Email      SMS      Push<br>             \       |       /<br>              \      |      /<br>               OrderService</pre><p>OrderService doesn&#39;t care whether it received:</p><pre>EmailNotification<br>SMSNotification<br>PushNotification</pre><p>It only knows:</p><pre>notification.send();</pre><p>It knows the <strong>contract</strong>, not the implementation.</p><p>That’s loose coupling.</p><h3>What does “loose coupling” actually mean?</h3><p>A simple definition:</p><blockquote><strong><em>Loose coupling means one component knows as little as reasonably possible about the internal details of another component.</em></strong></blockquote><p>OrderService doesn&#39;t need to know:</p><ul><li>how email is sent</li><li>which email provider is used</li><li>how SMS works</li><li>how Push works</li><li>how the object was created</li></ul><p>It only needs to know:</p><pre>Notification</pre><p>and its contract:</p><pre>send()</pre><p>That’s it.</p><h3>Why does DIP make testing easier?</h3><p>This is one of the most practical benefits.</p><p>Suppose we have:</p><pre>class OrderService {</pre><pre>    EmailService email = new EmailService();<br>}</pre><p>Now when testing OrderService, it has created its own real dependency.</p><p>That’s inconvenient.</p><p>With DIP:</p><pre>class OrderService {</pre><pre>    private final Notification notification;</pre><pre>    OrderService(Notification notification) {<br>        this.notification = notification;<br>    }<br>}</pre><p>During testing, we can provide a fake implementation:</p><pre>class FakeNotification implements Notification {</pre><pre>    public void send() {<br>        // fake behavior<br>    }<br>}</pre><p>Then:</p><pre>OrderService service =<br>    new OrderService(new FakeNotification());</pre><p>We can test the order logic without actually sending an email.</p><p>This is why dependency injection is so useful in real applications.</p><h3>DIP is not simply “use interfaces everywhere”</h3><p>This is an important clarification.</p><p>DIP does <strong>not</strong> mean:</p><blockquote><em>“Every class must have an interface.”</em></blockquote><p>The actual idea is about <strong>dependency direction</strong>.</p><p>High-level business logic shouldn’t be unnecessarily tied to low-level implementation details.</p><p>An interface is one common way of creating that boundary.</p><p>The goal is:</p><pre>High-level policy<br>       ↓<br>   Abstraction<br>       ↑<br>Low-level implementation</pre><p>rather than:</p><pre>High-level policy<br>       ↓<br>Concrete implementation</pre><h3>One important distinction: implementation change vs contract change</h3><p>This is where abstraction becomes really useful.</p><p>Suppose:</p><pre>interface Notification {<br>    void send();<br>}</pre><p>Our email implementation internally uses Provider A.</p><p>Tomorrow we change it to Provider B.</p><pre>Provider A<br>    ↓<br>Provider B</pre><p>But the contract remains:</p><pre>send()</pre><p>OrderService doesn&#39;t care.</p><p>That’s exactly what the abstraction protected us from.</p><p>But suppose we change the contract itself:</p><pre>void send();</pre><p>becomes:</p><pre>void send(User user);</pre><p>Now the contract has changed.</p><p>Naturally, implementations and callers may need to change.</p><p>DIP doesn’t promise:</p><blockquote><em>“Clients will never need modification.”</em></blockquote><p>It promises something more realistic:</p><blockquote><strong><em>Implementation details can change without unnecessarily forcing changes into the code that depends on the abstraction.</em></strong></blockquote><p>That’s an important distinction.</p><h3>How are DIP and LSP connected?</h3><p>This is another interesting relationship.</p><p>DIP says:</p><blockquote><em>Depend on the abstraction.</em></blockquote><p>LSP says:</p><blockquote><em>Make sure implementations can actually behave as valid substitutes for that abstraction.</em></blockquote><p>For example:</p><pre>Notification notification = new SMSNotification();</pre><pre>notification.send();</pre><p>DIP allows us to write code this way.</p><p>LSP makes sure that this is actually safe and meaningful.</p><p>So you can think of it like this:</p><blockquote><strong><em>DIP gives us the abstraction. LSP makes that abstraction trustworthy.</em></strong></blockquote><p>They are strongly related, but they are not the same principle.</p><h3>How are DIP and OCP connected?</h3><p>They’re also closely connected.</p><p>Suppose:</p><pre>OrderService → EmailService</pre><p>If we want SMS, we may have to modify OrderService.</p><p>That’s bad for OCP.</p><p>But if we have:</p><pre>OrderService → Notification<br>                       ↑<br>                 Email / SMS / Push</pre><p>we can add:</p><pre>class SMSNotification implements Notification</pre><p>without changing OrderService.</p><p>So:</p><pre>DIP<br> ↓<br>Depend on abstraction<br> ↓<br>Reduce coupling<br> ↓<br>Implementations become replaceable<br> ↓<br>New implementations can be added<br> ↓<br>OCP becomes easier to achieve</pre><p>This is why the SOLID principles can feel interconnected.</p><p>They are.</p><p>But they are still solving different problems.</p><h3>So, are the SOLID principles really separate?</h3><p>Yes and no.</p><p>They are separate principles, but they work together.</p><p>A useful mental model is:</p><pre>SRP<br>↓<br>Keep responsibilities separated</pre><pre>OCP<br>↓<br>Make extension easier</pre><pre>LSP<br>↓<br>Make substitutions safe</pre><pre>ISP<br>↓<br>Keep abstractions focused</pre><pre>DIP<br>↓<br>Reduce unnecessary dependency on concrete implementations</pre><p>And together:</p><pre>SOLID<br>                   |<br>          Control the impact<br>             of change<br>                   |<br>        ---------------------<br>        |         |         |<br>      SRP        DIP       OCP<br>        |          |         |<br>   separation   coupling   extension<br>                   |<br>                  LSP<br>                   |<br>              trustworthy<br>              abstractions<br>                   |<br>                  ISP<br>                   |<br>             focused contracts</pre><p>This isn’t a strict dependency graph.</p><p>It is simply a way to see how the principles support each other.</p><h3>The simplest way I now remember SOLID</h3><p>Whenever I’m designing a class, I can ask five questions.</p><h3>SRP</h3><blockquote><strong><em>Is this class responsible for unrelated things?</em></strong></blockquote><h3>OCP</h3><blockquote><strong><em>If a new requirement comes, will I have to keep modifying this existing code?</em></strong></blockquote><h3>LSP</h3><blockquote><strong><em>Can I safely replace this implementation with another implementation of the abstraction?</em></strong></blockquote><h3>ISP</h3><blockquote><strong><em>Am I forcing something to depend on methods it doesn’t need?</em></strong></blockquote><h3>DIP</h3><blockquote><strong><em>Is my high-level code unnecessarily tied to a concrete implementation?</em></strong></blockquote><p>That’s much easier to remember than five textbook definitions.</p><h3>One more important observation</h3><p>SOLID is <strong>not about writing more classes</strong>.</p><p>It is not:</p><pre>1 class<br>→ 5 interfaces<br>→ 12 abstractions<br>→ 20 design patterns</pre><p>That would just create unnecessary complexity.</p><p>The goal is not to make code look “architectural.”</p><p>The goal is:</p><blockquote><strong><em>Make change easier to manage.</em></strong></blockquote><p>If a small piece of code will never change and doesn’t need an abstraction, don’t create one just because SOLID says so.</p><p>Good engineering is about finding the right level of abstraction.</p><h3>Final Mental Model</h3><p>If I had to reduce the entire article to a few lines:</p><p><strong>SRP</strong></p><blockquote><em>Keep unrelated responsibilities apart.</em></blockquote><p><strong>OCP</strong></p><blockquote><em>When new behavior is added, prefer extending the system instead of repeatedly modifying stable code.</em></blockquote><p><strong>LSP</strong></p><blockquote><em>Implementations must keep the promises made by their abstraction.</em></blockquote><p><strong>ISP</strong></p><blockquote><em>Don’t force clients or implementations to depend on things they don’t need.</em></blockquote><p><strong>DIP</strong></p><blockquote><em>Don’t unnecessarily tie high-level business logic to low-level implementation details.</em></blockquote><p>And the bigger idea behind all of them:</p><blockquote><strong><em>SOLID is ultimately about controlling change.</em></strong></blockquote><p>We cannot stop requirements from changing.</p><p>We cannot stop APIs from changing.</p><p>We cannot stop businesses from asking for SMS after building email.</p><p>We cannot stop developers from replacing libraries or databases.</p><p>What we can do is design our code so that:</p><pre>A change happens<br>      ↓<br>It stays as local as possible<br>      ↓<br>Unrelated code remains untouched</pre><p>That, to me, is the real value of SOLID.</p><p>Not five definitions to memorize.</p><p>Not five interview answers.</p><p>Just <strong>better boundaries, lower coupling, safer abstractions, and less unnecessary ripple when the system changes.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc10167ab6e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Dating Apps Handle Endless Swipes, Heavy Chats & Location Radar — Explained Simply]]></title>
            <link>https://medium.com/@vedantrathore627/how-dating-apps-handle-endless-swipes-heavy-chats-location-radar-explained-simply-8c97633f31df?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c97633f31df</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 19:57:20 GMT</pubDate>
            <atom:updated>2026-02-26T19:57:20.205Z</atom:updated>
            <content:encoded><![CDATA[<p>“How do these apps handle so many swipes… so many long reads… and still show me on your location radar?”</p><p>Fair question.<br> Most people use dating apps, but very few know how they actually work.<br> Here’s the simplest, cleanest breakdown — no engineering jargon, just plain English.</p><ol><li><strong>How Dating Apps Handle Millions of Swipes</strong></li></ol><p>Swiping feels small and harmless to us,<br>but to the app, each swipe is a <strong>data event</strong>.</p><p>When you swipe:</p><ol><li>Your phone sends:</li></ol><ul><li>Your <strong>user ID</strong></li><li>Who you swiped on</li><li>Left or Right swipe</li><li>Timestamp</li></ul><p>2. The backend stores it in a <strong>Swipe Database</strong></p><p>3. If both users liked each other, backend triggers:</p><ul><li><strong>Match created</strong></li><li><strong>Chat room opened</strong></li><li><strong>Notifications sent</strong></li></ul><p>Apps handle millions of swipes by:</p><ul><li>Using <strong>caching</strong> (data stored in memory temporarily)</li><li>Using <strong>distributed servers</strong></li><li>Using <strong>small, lightweight swipe requests</strong></li></ul><p>Result: swipes feel instant.</p><h3>2. How They Handle “Read Heavy” Chats</h3><p>When you open a long conversation:</p><ul><li>Your app loads messages through <strong>WebSockets</strong></li><li>Only recent messages load first</li><li>Older messages load as you scroll</li><li>Images stay on a <strong>CDN</strong> (fast global storage)</li></ul><p>This keeps reading fast even if:</p><ul><li>You have 1,000 messages</li><li>You have many active chats</li><li>You switch networks</li></ul><p>Backend chat servers are optimized to handle <strong>millions of messages per minute</strong>.</p><p>So yes — even your “essay chats” load instantly.</p><h3>3. How Location Radar Actually Works</h3><p>This was the girl’s biggest confusion.</p><p>Dating apps <strong>do NOT track real-time movement</strong>.<br> They only update your location <strong>periodically</strong>, like:</p><ul><li>When you open the app</li><li>Every few minutes</li><li>When the OS updates GPS</li></ul><p>Then:</p><ol><li>Your latitude &amp; longitude go to the server</li><li>Backend compares distance using the <strong>Haversine formula</strong></li><li>If you fall inside her distance preference → your profile appears</li><li>That’s why she sees you “on radar”</li></ol><p>It’s NOT tracking.<br> It’s NOT stalking.<br> It’s just simple maths + GPS updates.</p><h3>4. Why She Saw You at That Exact Time</h3><p>There are two reasons:</p><h3>1. You opened the app around that time</h3><p>GPS got refreshed → you entered her radius.</p><h3>2. She fits your filter AND you fit hers</h3><p>Age range, gender preference, distance, activity.</p><h3>5. The Whole System in One Sentence</h3><p>Dating apps survive heavy swiping, heavy reading, and accurate location matching because they use:</p><ul><li>Lightweight swipe requests</li><li>Fast databases</li><li>Real-time messaging frameworks</li><li>GPS-based distance calculation</li></ul><p>Behind that simple swipe UI is a <strong>massive system design</strong>.</p><h3>Final Thoughts</h3><p>Most people think dating apps are simple.<br> But the girl I matched with asked the perfect technical question — and she’s right.<br> These apps quietly handle:</p><ul><li>Millions of swipes</li><li>Thousands of chats</li><li>Continuous GPS updates</li><li>Matches, filters, rankings, safety checks</li></ul><p>All in milliseconds.</p><p>It’s one of the most complex systems built for one of the simplest human goals:<br> <strong>connection.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c97633f31df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID in Real Life: A Practical LLD Walkthrough Using a Game System]]></title>
            <link>https://medium.com/@vedantrathore627/solid-in-real-life-a-practical-lld-walkthrough-using-a-game-system-30d3cc157b21?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d3cc157b21</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[hiring]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 23:20:40 GMT</pubDate>
            <atom:updated>2026-01-12T23:20:40.046Z</atom:updated>
            <content:encoded><![CDATA[<p>Most articles explain <strong>SOLID principles</strong> with toy examples.</p><p>Interfaces named Animal, methods named makeSound(), and zero connection to real systems.</p><p>This article is different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9_51lS-raIora234G-1sQ.png" /></figure><p>Here, I’ll walk through a <strong>real Low-Level Design (LLD)</strong> and explain <strong>where SOLID actually shows up in code</strong>, using a game system that includes:</p><ul><li>Game orchestration</li><li>Board &amp; cells</li><li>Players &amp; pieces</li><li>Winning strategies</li><li>Notifications using Observer</li><li>Piece creation using Factory</li></ul><p>No theory. Only <strong>practical reasoning</strong>.</p><h3>1️⃣ Single Responsibility Principle (SRP) — Done Right</h3><p>SRP means <em>one reason to change</em> — not <em>small classes</em>.</p><h3>🎮 Game (Orchestrator)</h3><p><strong>Responsibility:</strong></p><ul><li>Control game flow</li><li>Rotate turns</li><li>Trigger win checks</li><li>Notify observers</li></ul><p><strong>What it does NOT do:</strong></p><ul><li>Decide winning logic</li><li>Store board rules</li><li>Decide notification channels</li></ul><p>That logic is delegated.</p><p>✔ SRP respected.</p><h3>🧱 Board</h3><p><strong>Responsibility:</strong></p><ul><li>Store grid state</li><li>Validate and apply moves</li></ul><p><strong>What it does NOT do:</strong></p><ul><li>Decide winners</li><li>Notify users</li><li>Control turns</li></ul><p>✔ Clean separation.</p><h3>🏆 WinningStrategy</h3><p>Each implementation handles <strong>only one thing</strong></p><blockquote><em>“How do we decide if someone won or if it’s a draw?”</em></blockquote><p>Adding a new rule means:</p><ul><li>Add a new class</li><li>Do NOT modify existing code</li></ul><p>✔ SRP + OCP together.</p><h3>2️⃣ Open/Closed Principle (OCP) — Real Extensibility</h3><h3>Winning Strategy</h3><pre>Game game = new Game(3, new NormalWinningStrategy());</pre><p>Tomorrow:</p><ul><li>AdvancedWinningStrategy</li><li>NxNWinningStrategy</li></ul><p>No change in Game.</p><p>✔ Open for extension<br> ✔ Closed for modification</p><h3>Notifications</h3><p>The game doesn’t know <em>how</em> notifications happen.</p><p>It only knows:</p><pre>observer.notify(message);</pre><p>You can add</p><ul><li>In-game notification</li><li>Email</li><li>SMS</li><li>Analytics</li><li>Audit logs</li></ul><p>Without touching Game.</p><p>✔ This is <strong>real OCP</strong>, not academic.</p><h3>3️⃣ Liskov Substitution Principle (LSP) — Naturally Achieved</h3><p>Because:</p><ul><li>Interfaces are clean</li><li>No instanceof</li><li>No type casting</li></ul><p>Anywhere a WinningStrategy or Observer is used, <strong>any implementation works</strong>.</p><p>That’s LSP done <em>correctly</em>, without forcing it.</p><h3>4️⃣ Interface Segregation Principle (ISP) — Small, Honest Interfaces</h3><h3>Observer</h3><pre>void notify(String message);</pre><p>Nothing extra. Nothing unused.</p><h3>WinningStrategy</h3><pre>boolean checkWinner(...);<br>boolean isDraw(...);</pre><p>Each method belongs there.</p><p>✔ No bloated interfaces<br> ✔ No dummy implementations</p><p>ISP follows naturally when SRP is respected.</p><h3>5️⃣ Dependency Inversion Principle (DIP) — The Most Important One</h3><h3>Game depends on abstractions</h3><pre>private WinningStrategy winningStrategy;<br>private List&lt;Observer&gt; observers;</pre><p>Not on concrete classes.</p><p>This means:</p><ul><li>Game doesn’t care <em>what</em> the strategy is</li><li>Game doesn’t care <em>how</em> notifications are sent</li></ul><p>✔ High-level logic is independent of low-level details<br> ✔ True DIP</p><h3>Observer vs Strategy — Clearing a Common Confusion</h3><blockquote><em>“If we have Email, SMS, In-Game notifications — isn’t that Strategy?</em></blockquote><p><strong>No. And here’s why.</strong></p><h3>Strategy answers:</h3><blockquote>Which one behavior do I choose?</blockquote><h3>Observer answers:</h3><blockquote>Who should be notified when something happens?</blockquote><p>In this design:</p><ul><li>Multiple observers receive the same event</li><li>They coexist, not replace each other</li></ul><p>That’s <strong>Observer</strong>, not Strategy.</p><blockquote><em>Strategy → interchangeable<br> Observer → additive</em></blockquote><p>Full Java Code: <a href="https://github.com/VedantRathor/AdvanceLLD/tree/main/LLDProblems/TicTacToe">https://github.com/VedantRathor/AdvanceLLD/tree/main/LLDProblems/TicTacToe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d3cc157b21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 1970: Last Day Where You Can Still Cross — When Brute Force Meets Monotonic Thinking]]></title>
            <link>https://medium.com/@vedantrathore627/leetcode-1970-last-day-where-you-can-still-cross-when-brute-force-meets-monotonic-thinking-898da7084f98?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/898da7084f98</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 05:07:53 GMT</pubDate>
            <atom:updated>2025-12-31T05:07:53.440Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode 1970: Last Day Where You Can Still Cross — When Brute Force Meets Monotonic Thinking</h3><p>Some problems look like graph traversal problems.</p><p>This one looks like that…<br> but it’s actually a <strong>binary search problem hiding inside BFS/DFS</strong>.</p><p>And once you see that, the solution becomes clean and powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*tZkKeiYmV25keRoXX4B4Hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*bcWPSna4Wsfs_IJoZmRxUA.png" /></figure><h3>🔍 Problem in Simple Words</h3><p>You’re given a grid:</p><ul><li>0 → land</li><li>1 → water</li></ul><p>Initially (day 0), <strong>everything is land</strong>.</p><p>Each day:</p><ul><li>one cell gets flooded (turns into water)</li></ul><p>Your goal:</p><blockquote><em>Find the </em><strong><em>last day</em></strong><em> when it’s still possible to walk<br> from </em><strong><em>top row → bottom row</em></strong><em><br> using only land cells<br> moving only in 4 directions.</em></blockquote><p>You can start and end at <strong>any column</strong>.</p><h3>🧠 My First Thought (Naive Simulation)</h3><p>Since the question asks for the <strong>last day</strong>, my first instinct was:</p><ul><li>Start from the <strong>last day</strong></li><li>Simulate the grid</li><li>Run DFS / BFS to check if a path exists</li><li>If not, remove one day and try again</li></ul><p>Sounds logical.</p><p>But then reality hits.</p><h3>❌ Why This Fails</h3><p>Worst case:</p><pre>days ≈ 10^4<br>each BFS ≈ n × m</pre><p>That’s easily <strong>10⁸+ operations</strong>.</p><p>⚠️ TLE waiting to happen.</p><h3>💡 Key Insight (The Turning Point)</h3><p>This sentence changes everything:</p><blockquote><em>“Return the </em><strong><em>last day</em></strong><em> where it is possible to cross.”</em></blockquote><p>That implies <strong>monotonicity</strong>.</p><h3>What does that mean?</h3><ul><li>If crossing is possible on day d<br> → it must also be possible on <strong>all days &lt; d</strong></li><li>If crossing is impossible on day d<br> → it will remain impossible for <strong>all days &gt; d</strong></li></ul><p>This is a <strong>classic binary search on the answer</strong>.</p><h3>🚀 Final Strategy</h3><ol><li>Binary search on <strong>day</strong></li><li>For a given mid day:</li></ol><ul><li>flood the grid up to that day</li><li>run BFS from <strong>top row</strong></li></ul><p>3. If we reach bottom → crossing is possible</p><p>4. Move binary search accordingly</p><h3>🧩 How BFS Is Used Here</h3><p>For a fixed day:</p><ul><li>build a temporary grid</li><li>mark flooded cells</li><li>push all <strong>top-row land cells</strong> into a queue</li><li>BFS until:</li><li>bottom row reached → success</li><li>queue exhausted → failure</li></ul><p>This keeps traversal clean and controlled</p><h3>✅ C++ Implementation</h3><pre>class Solution {<br>private:<br>    vector&lt;vector&lt;int&gt;&gt; directions = {{0,1},{1,0},{0,-1},{-1,0}};<br>    <br>    bool valid(int n, int m, int i, int j){<br>        return i &gt;= 0 &amp;&amp; j &gt;= 0 &amp;&amp; i &lt; n &amp;&amp; j &lt; m;<br>    }<br><br>    bool isPossible(vector&lt;vector&lt;int&gt;&gt;&amp; cells, int day, int n, int m){<br>        vector&lt;vector&lt;int&gt;&gt; temp(n, vector&lt;int&gt;(m, 0));<br><br>        // flood till &#39;day&#39;<br>        for(int i = 0; i &lt; day; i++){<br>            temp[cells[i][0] - 1][cells[i][1] - 1] = 1;<br>        }<br><br>        queue&lt;pair&lt;int,int&gt;&gt; q;<br><br>        // start from top row<br>        for(int j = 0; j &lt; m; j++){<br>            if(temp[0][j] == 0){<br>                q.push({0, j});<br>                temp[0][j] = -1;<br>            }<br>        }<br><br>        while(!q.empty()){<br>            auto [x, y] = q.front();<br>            q.pop();<br><br>            if(x == n - 1) return true;<br><br>            for(auto &amp;dir : directions){<br>                int nx = x + dir[0];<br>                int ny = y + dir[1];<br>                if(valid(n, m, nx, ny) &amp;&amp; temp[nx][ny] == 0){<br>                    temp[nx][ny] = -1;<br>                    q.push({nx, ny});<br>                }<br>            }<br>        }<br>        return false;<br>    }<br><br>public:<br>    int latestDayToCross(int n, int m, vector&lt;vector&lt;int&gt;&gt;&amp; cells) {<br>        int s = 0, e = cells.size(), last = 0;<br><br>        while(s &lt;= e){<br>            int mid = s + (e - s) / 2;<br>            if(isPossible(cells, mid, n, m)){<br>                last = mid;<br>                s = mid + 1;<br>            } else {<br>                e = mid - 1;<br>            }<br>        }<br>        return last;<br>    }<br>};</pre><h3>⏱️ Time Complexity — Let’s Discuss 👇</h3><p>This is where things get interesting.</p><p>For each binary search step:</p><ul><li>we rebuild the grid</li><li>we run BFS</li></ul><p>So intuitively:</p><pre>Binary Search → log(days)<br>Each check → BFS over n × m</pre><p>💬 <strong>Question for you</strong></p><blockquote><em>How would you formally express the time complexity of this solution?<br> Is it </em><em>O((n×m) log(n×m))?<br> Or something tighter?</em></blockquote><p>Drop your reasoning in the comments — would love to see different takes.</p><p>(Thoughtful comments = better reach + deeper learning.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=898da7084f98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 840: Magic Squares in Grid — A Clean Implementation Problem (And Why That Matters)]]></title>
            <link>https://medium.com/@vedantrathore627/leetcode-840-magic-squares-in-grid-a-clean-implementation-problem-and-why-that-matters-c5ab04e98a01?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5ab04e98a01</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 07:11:38 GMT</pubDate>
            <atom:updated>2025-12-30T07:11:38.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode 840: Magic Squares in Grid — A Clean Implementation Problem (And Why That Matters)</h3><p>Not every problem is about clever tricks or fancy algorithms.</p><p>Some problems are about:</p><ul><li>how you <strong>structure your code</strong></li><li>how clearly you <strong>express intent</strong></li><li>how confidently you <strong>validate constraints</strong></li></ul><p><strong>Magic Squares in Grid</strong> is one of those problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*u30c_Q7HWjr52CHBmFl14w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*YBohdqpbtFgqtttzkgQHYA.png" /></figure><h3>🧠 My First Thought</h3><p>This problem is <strong>not algorithm-heavy</strong>.</p><p>It’s more about:</p><ul><li>validating conditions</li><li>avoiding missed edge cases</li><li>writing readable, maintainable logic</li></ul><p>So instead of compressing everything into one loop, I intentionally <strong>split the checks</strong>.</p><p>This mirrors how you’d write <strong>production code</strong>, not contest code.</p><h3>🧩 How I Structured the Solution</h3><p>I broke the validation into <strong>four independent checks</strong>:</p><ol><li><strong>All elements are valid and distinct</strong></li><li><strong>All rows have the same sum</strong></li><li><strong>All columns have the same sum</strong></li><li><strong>Both diagonals have the same sum</strong></li></ol><p>If <em>any</em> check fails → not a magic square.</p><h3>🏗️ Step 1: Validate Numbers (1–9 and distinct)</h3><pre>bool isAllElementsDistinctAndValid(int row, int col, vector&lt;vector&lt;int&gt;&gt; &amp;grid) {<br>    unordered_set&lt;int&gt; st;<br><br>    for (int i = row; i &lt;= row + 2; i++) {<br>        for (int j = col; j &lt;= col + 2; j++) {<br>            if (grid[i][j] &gt;= 1 &amp;&amp; grid[i][j] &lt;= 9) {<br>                st.insert(grid[i][j]);<br>            } else {<br>                return false;<br>            }<br>        }<br>    }<br><br>    return st.size() == 9;<br>}</pre><p>This ensures:</p><ul><li>only numbers 1 to 9</li><li>no duplicates</li></ul><h3>🧮 Step 2: Check Rows</h3><pre>bool areRowsValid(int row, int col, vector&lt;vector&lt;int&gt;&gt; &amp;grid, int expectedSum) {<br>    for (int i = row; i &lt;= row + 2; i++) {<br>        int total = 0;<br>        for (int j = col; j &lt;= col + 2; j++) {<br>            total += grid[i][j];<br>        }<br>        if (total != expectedSum) return false;<br>    }<br>    return true;<br>}</pre><h3>📐 Step 3: Check Columns</h3><pre>bool areColumnsValid(int row, int col, vector&lt;vector&lt;int&gt;&gt; &amp;grid, int expectedSum) {<br>    for (int j = col; j &lt;= col + 2; j++) {<br>        int total = 0;<br>        for (int i = row; i &lt;= row + 2; i++) {<br>            total += grid[i][j];<br>        }<br>        if (total != expectedSum) return false;<br>    }<br>    return true;<br>}</pre><h3>❌ Step 4: Check Diagonals</h3><pre>bool areDiagonalsValid(int row, int col, vector&lt;vector&lt;int&gt;&gt; &amp;grid, int expectedSum) {<br>    int total = 0;<br><br>    for (int i = 0; i &lt; 3; i++) {<br>        total += grid[row + i][col + i];<br>    }<br>    if (total != expectedSum) return false;<br><br>    total = 0;<br>    for (int i = 0; i &lt; 3; i++) {<br>        total += grid[row + i][col + 2 - i];<br>    }<br><br>    return total == expectedSum;<br>}</pre><h3>🧪 Final Validation Wrapper</h3><pre>bool isMagicGrid(int row, int col, vector&lt;vector&lt;int&gt;&gt; &amp;grid) {<br>    if (!isAllElementsDistinctAndValid(row, col, grid)) return false;<br><br>    int expectedSum = 0;<br>    for (int j = col; j &lt;= col + 2; j++) {<br>        expectedSum += grid[row][j];<br>    }<br><br>    return areRowsValid(row, col, grid, expectedSum) &amp;&amp;<br>           areColumnsValid(row, col, grid, expectedSum) &amp;&amp;<br>           areDiagonalsValid(row, col, grid, expectedSum);<br>}</pre><h3>🔁 Final Loop Over the Grid</h3><pre>int numMagicSquaresInside(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {<br>    int nr = grid.size();<br>    int nc = grid[0].size();<br>    int count = 0;<br><br>    for (int row = 0; row + 2 &lt; nr; row++) {<br>        for (int col = 0; col + 2 &lt; nc; col++) {<br>            if (isMagicGrid(row, col, grid)) {<br>                count++;<br>            }<br>        }<br>    }<br><br>    return count;<br>}</pre><h3>🧠 Time Complexity — Let’s Discuss</h3><p>For each cell (row, col):</p><ul><li>distinct check → constant (9 elements)</li><li>row checks → constant</li><li>column checks → constant</li><li>diagonal checks → constant</li></ul><p>So intuitively:</p><p>O(n × m × constant)</p><p>But here’s my <strong>question to you</strong> 👇<br> 💬 <strong>How would you formally describe the time complexity of this solution?</strong><br> Would you simplify it as O(n × m)? Why or why not?</p><p>Drop your reasoning in the comments — would love to hear different perspectives.</p><p>(Discussions like this help everyone learn.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ab04e98a01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 756: Pyramid Transition Matrix — A Recursion Problem That Forces You to Think Differently]]></title>
            <link>https://medium.com/@vedantrathore627/leetcode-756-pyramid-transition-matrix-a-recursion-problem-that-forces-you-to-think-differently-0cf7fe910de3?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cf7fe910de3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 08:46:29 GMT</pubDate>
            <atom:updated>2025-12-29T08:46:29.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode 756: Pyramid Transition Matrix — A Recursion Problem That Forces You to Think Differently</h3><p>Some problems are hard because they are big.<br>Some problems are hard because they <strong>don’t fit your usual recursion template</strong>.</p><p><strong>Pyramid Transition Matrix</strong> is the second kind.</p><p>When I first read it, I realized:</p><p>This is not “normal recursion”.<br>This is <strong>controlled backtracking with two evolving states</strong>.</p><p>Let’s walk through it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*SyQrQcmHHO0leOvwZ_KsMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*0VYcvIEvcmm6BN2K5JX8TQ.png" /></figure><h3>🔍 Problem in Simple Words</h3><p>You are stacking blocks to form a pyramid.</p><p>Rules:</p><ul><li>Each block has a color (a letter)</li><li>Each row is <strong>one block shorter</strong> than the row below</li><li>A block on top depends on <strong>two adjacent blocks below</strong></li><li>Only specific patterns are allowed</li></ul><p>Each allowed pattern is a 3-letter string:</p><p>&quot;ABC&quot; → A (left), B (right) → C on top</p><p>You’re given:</p><ul><li>a bottom row (string)</li><li>a list of allowed patterns</li></ul><p>Your task:</p><blockquote><em>Can you build the pyramid </em><strong><em>all the way to the top</em></strong><em> using only allowed patterns?</em></blockquote><h3>🧠 Why This Problem Feels Hard</h3><p>Because you’re doing <strong>two things at the same time</strong>:</p><ol><li>Building the <strong>next row</strong></li><li>Recursively checking whether that row can eventually lead to a single block</li></ol><p>You’re not just recursing on one variable — <br> you’re managing:</p><ul><li>an index in the current row</li><li>a partially formed next row</li></ul><p>This makes the recursion <strong>stateful and layered</strong>.</p><h3>💡 Key Insight</h3><p>Think of the problem in <strong>levels</strong>:</p><ul><li>First, try to build <strong>one full row above</strong></li><li>Once that row is complete, treat it as a new base</li><li>Repeat until the length becomes 1</li></ul><p>So recursion has <strong>two dimensions</strong>:</p><ul><li>horizontal → forming the next row</li><li>vertical → moving up the pyramid</li></ul><h3>🏗️ Preprocessing (Very Important)</h3><p>We convert allowed into a fast lookup:</p><p>unordered_map&lt;string, vector&lt;char&gt;&gt; wordToChars; // &quot;AB&quot; -&gt; [&#39;C&#39;, &#39;D&#39;, ...]</p><p>This avoids scanning allowed repeatedly and makes recursion feasible.</p><h3>🔁 Recursive Strategy (Core Logic)</h3><p>Let’s define a helper:</p><p>isPyramidPossible(currBottom, idx, newBottom)</p><h3>Base Case</h3><p>If currBottom.length() == 1<br> → Pyramid successfully built.</p><h3>Case 1: Finished building current level</h3><p>If idx == currBottom.length() - 1:</p><ul><li>we’ve formed a full newBottom</li><li>now recursively try to build on top of it</li></ul><h3>Case 2: Still building the next row</h3><ul><li>take two adjacent characters</li><li>find all possible top characters</li><li>try each one (backtracking)</li><li>if any path succeeds → return true</li></ul><h3>✅ My C++ Implementation</h3><pre>class Solution {<br>public:<br><br>    bool isPyramidPossible(<br>        string &amp;currBottom,<br>        int idx,<br>        string &amp;newBottom,<br>        unordered_map&lt;string, vector&lt;char&gt;&gt; &amp;wordToChars<br>    ) {<br>        if (currBottom.length() == 1) {<br>            return true;<br>        }<br><br>        if (idx == currBottom.length() - 1) {<br>            string next;<br>            return isPyramidPossible(newBottom, 0, next, wordToChars);<br>        }<br><br>        string key;<br>        key.push_back(currBottom[idx]);<br>        key.push_back(currBottom[idx + 1]);<br><br>        for (char ch : wordToChars[key]) {<br>            newBottom.push_back(ch);<br>            if (isPyramidPossible(currBottom, idx + 1, newBottom, wordToChars)) {<br>                return true;<br>            }<br>            newBottom.pop_back(); // backtrack<br>        }<br><br>        return false;<br>    }<br><br>    bool pyramidTransition(string bottom, vector&lt;string&gt;&amp; allowed) {<br>        unordered_map&lt;string, vector&lt;char&gt;&gt; wordToChars;<br><br>        for (auto &amp;s : allowed) {<br>            string key;<br>            key.push_back(s[0]);<br>            key.push_back(s[1]);<br>            wordToChars[key].push_back(s[2]);<br>        }<br><br>        string next;<br>        return isPyramidPossible(bottom, 0, next, wordToChars);<br>    }<br>};</pre><h3>🧩 Why This Problem Is Important</h3><p>This problem teaches:</p><ul><li>controlled recursion</li><li>backtracking with partial state</li><li>how to decompose problems <strong>layer by layer</strong></li><li>how preprocessing enables feasible recursion</li></ul><p>These patterns show up in:</p><ul><li>grammar parsing</li><li>configuration generation</li><li>dependency resolution</li><li>rule-based systems</li></ul><h3>❓ Let’s Talk Time Complexity (Open Question)</h3><p>This is where things get interesting.</p><p>The time complexity is <strong>not immediately obvious</strong>.</p><p>It depends on:</p><ul><li>branching factor (number of valid top blocks per pair)</li><li>length of the bottom row</li><li>pruning effectiveness</li></ul><p>💬 <strong>Question for you</strong>:</p><blockquote><em>How would you describe the time complexity of this solution?<br> Is it exponential? Can memoization help? If yes, how?</em></blockquote><p>Drop your thoughts in the comments — would love to discuss.</p><p>(Engaging discussions = better learning + better reach 😉)</p><p>Connect with me: <a href="https://www.linkedin.com/in/vedant-rathore-8bb905211/">https://www.linkedin.com/in/vedant-rathore-8bb905211/</a></p><p>Git: <a href="https://github.com/VedantRathor/Projects-Hub">https://github.com/VedantRathor/Projects-Hub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cf7fe910de3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 1351: Count Negative Numbers in a Sorted Matrix — Using Order, Not Force]]></title>
            <link>https://medium.com/@vedantrathore627/leetcode-1351-count-negative-numbers-in-a-sorted-matrix-using-order-not-force-017d159a3fab?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/017d159a3fab</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 11:30:42 GMT</pubDate>
            <atom:updated>2025-12-28T11:30:42.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode 1351: Count Negative Numbers in a Sorted Matrix — Using Order, Not Force</h3><p>Some problems are easy.<br>Some problems are <em>easy but revealing</em>.</p><p>This one belongs to the second category.</p><p>The real question here is not <strong>how fast you can code</strong>, but <strong>how well you use the structure given to you</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*IiyE__I5Q_BGmdn9KVyGjA.png" /></figure><h3>🔍 Problem in Simple Words</h3><p>You’re given a matrix where:</p><ul><li>each <strong>row is sorted in non-increasing order</strong></li><li>each <strong>column is also sorted in non-increasing order</strong></li></ul><p>Your task:</p><blockquote><em>Count how many numbers in the matrix are </em><strong><em>negative</em></strong><em>.</em></blockquote><h3>🧠 First Thoughts (Three Ways to Solve)</h3><h3>1️⃣ Brute Force</h3><p>Check every element.</p><pre>Time Complexity: O(m × n)</pre><p>Works, but ignores the <strong>sorted nature</strong> of the matrix.</p><h3>2️⃣ Binary Search per Row</h3><p>Each row is sorted, so:</p><ul><li>binary search for the first negative number</li><li>count elements after it</li></ul><pre>Time Complexity: O(m log n)</pre><p>Better — but still not optimal.</p><h3>3️⃣ Optimal Solution — Use Both Row &amp; Column Order</h3><p>This is where the problem becomes interesting.</p><h3>Key Observation</h3><p>If grid[row][col] is <strong>negative</strong>, then:</p><ul><li>every element <strong>to the right</strong> in that row is also negative</li><li>every element <strong>below</strong> in that column is also negative</li></ul><p>So instead of scanning everything, we <strong>walk the matrix intelligently</strong>.</p><h3>🚀 Optimal Strategy (O(m + n))</h3><ol><li>Start from the <strong>top-right corner</strong></li><li>If the current value is <strong>non-negative</strong>:</li></ol><ul><li>move <strong>down</strong></li></ul><p>3. If the current value is <strong>negative</strong>:</p><ul><li>all values below are also negative</li><li>add (remaining rows) to the answer</li><li>move <strong>left</strong></li></ul><p>Each move reduces either a row or a column — never both.</p><p>So total steps ≤ m + n.</p><h3>✅ C++ Implementation</h3><pre>class Solution {<br>public:<br>    int countNegatives(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {<br>        int nr = grid.size();<br>        int nc = grid[0].size();<br><br>        int count = 0;<br>        int row = 0, col = nc - 1;<br><br>        while (col &gt;= 0 &amp;&amp; row &lt; nr) {<br>            if (grid[row][col] &gt;= 0) {<br>                row++;<br>            } else {<br>                count += (nr - row);<br>                col--;<br>            }<br>        }<br><br>        return count;<br>    }<br>};</pre><h3>⏱️ Complexity Analysis</h3><ul><li><strong>Time:</strong> O(m + n)</li><li><strong>Space:</strong> O(1)</li></ul><p>This is the <strong>best possible solution</strong>.</p><h3>🎯 Why Recruiters Like This Problem</h3><p>This problem tests:</p><ul><li>ability to <strong>read constraints carefully</strong></li><li>recognizing <strong>monotonic structures</strong></li><li>avoiding unnecessary computation</li><li>writing <strong>clean, confident logic</strong></li></ul><p>These skills translate directly to:</p><ul><li>query optimization</li><li>analytics pipelines</li><li>backend performance tuning</li></ul><h3>🧩 Final Takeaway</h3><blockquote><em>If a problem tells you something is sorted,<br> it’s not extra information — it’s the solution.</em></blockquote><p>Good engineers don’t brute force.<br> They <strong>use order to their advantage</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=017d159a3fab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 2402: Meeting Rooms III — Thinking Like a Scheduler, Not Just a Coder]]></title>
            <link>https://medium.com/@vedantrathore627/leetcode-2402-meeting-rooms-iii-thinking-like-a-scheduler-not-just-a-coder-a574ec1ce6a9?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/a574ec1ce6a9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 10:22:26 GMT</pubDate>
            <atom:updated>2025-12-27T10:22:26.764Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode 2402: Meeting Rooms III — Thinking Like a Scheduler, Not Just a Coder</h3><p>Some problems don’t feel like DSA.<br> They feel like <strong>real systems</strong>.</p><p><strong>Meeting Rooms III</strong> is one of those problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJrbZ6WfsZqZTDdvtcUT9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7piNqjsEQbybI-hb4lH3Yw.png" /></figure><p>At first glance, it looks like a heap problem.<br> In reality, it tests whether you can <strong>simulate a real-world scheduler correctly</strong> under constraints.</p><p>Let’s break it down.</p><p>🧠 Problem Intuition</p><p>You are given:</p><ul><li>n meeting rooms (numbered 0 to n-1)</li><li>a list of meetings with <strong>unique start times</strong></li></ul><p>Rules:</p><ol><li>A meeting always goes to the <strong>lowest-numbered free room</strong></li><li>If no room is free, the meeting is <strong>delayed</strong></li><li>Delayed meetings:</li></ol><ul><li>keep the <strong>same duration</strong></li><li>start as soon as <em>any</em> room becomes free</li></ul><ol><li>If multiple rooms free up, the <strong>earliest meeting (original start)</strong> gets priority</li><li>At the end, return the <strong>room that hosted the most meetings</strong><br> (tie → lowest room number)</li></ol><p>This is not about clever math.<br> This is about <strong>correct simulation under ordering constraints</strong>.</p><h3>❌ Naive Thinking (Why It Fails)</h3><p>A naive idea might be:</p><ul><li>For each meeting, scan all rooms</li><li>Track availability manually</li><li>Shift meetings when needed</li></ul><p>But this quickly becomes:</p><ul><li>messy</li><li>error-prone</li><li>inefficient</li></ul><p>What we really need is:</p><ul><li>a way to <strong>always know which room frees first</strong></li><li>a way to <strong>process meetings in correct order</strong></li></ul><h3>💡 Key Insight</h3><p>We are managing <strong>two timelines</strong>:</p><ol><li><strong>Upcoming meetings (by start time)</strong></li><li><strong>Currently running meetings (by end time)</strong></li></ol><p>So we need:</p><ul><li>one structure ordered by <strong>meeting start</strong></li><li>one structure ordered by <strong>room free time</strong></li></ul><p>That’s it.</p><h3>🏗️ Data Structures Used</h3><h3>1️⃣ Meetings sorted by start time</h3><pre>set&lt;pair&lt;long, long&gt;&gt; startTimeWithEndTime;<br><br>(start, end)</pre><p>Stores:</p><pre>(start, end)</pre><p>This ensures:</p><ul><li>meetings are processed in correct chronological order</li></ul><h3>2️⃣ Active rooms ordered by free time</h3><pre>set&lt;pair&lt;long, long&gt;&gt; endTimeWithRoomId;</pre><p>Stores:</p><pre>(freeTime, roomId)</pre><p>This ensures:</p><ul><li>we always pick the room that becomes free <strong>earliest</strong></li><li>ties are resolved by <strong>room number</strong></li></ul><h3>3️⃣ Room availability</h3><pre>vector&lt;bool&gt; isFree;</pre><p>Simple and readable:</p><ul><li>true → room is free</li><li>false → room is occupied</li></ul><h3>🔁 Simulation Logic (Core Idea)</h3><p>For each meeting:</p><ol><li><strong>Free all rooms</strong> that finished before this meeting’s start</li><li>Try to get the <strong>lowest-numbered free room</strong></li><li>If available:</li></ol><ul><li>assign meeting</li></ul><ol><li>If not:</li></ol><ul><li>delay the meeting</li><li>assign it to the room that frees first</li><li>preserve duration</li></ul><p>Every assignment increments that room’s meeting count.</p><h3>✅ Final C++ Implementation</h3><pre>class Solution {<br>public:<br><br>    int getAvailableRoom(vector&lt;bool&gt; &amp;isFree) {<br><br>        for (int i = 0; i &lt; isFree.size(); i++) {<br>            if (isFree[i]) return i;<br>        }<br>        <br>        return -1;<br>    }<br><br>    int mostBooked(int n, vector&lt;vector&lt;int&gt;&gt;&amp; meetings) {<br>        set&lt;pair&lt;long,long&gt;&gt; endTimeWithRoomId;<br>        set&lt;pair&lt;long,long&gt;&gt; startTimeWithEndTime;<br>        unordered_map&lt;long,long&gt; roomIdWithCount;<br>        vector&lt;bool&gt; isFree(n, true);<br><br>        for (int i = 0; i &lt; meetings.size(); i++) {<br>            long start = meetings[i][0];<br>            long end = meetings[i][1] - 1;<br><br>            startTimeWithEndTime.insert({start, end});<br>        }<br><br>        while (startTimeWithEndTime.size() &gt; 0) {<br>            auto [start, end] = *startTimeWithEndTime.begin();<br>            startTimeWithEndTime.erase(startTimeWithEndTime.begin());<br><br>            // free the rooms<br>            while (endTimeWithRoomId.size() &gt; 0) {<br>                auto [freetime, roomId] = *endTimeWithRoomId.begin();<br><br>                if (freetime &lt;= start) {<br>                    isFree[roomId] = true;<br>                    endTimeWithRoomId.erase(endTimeWithRoomId.begin());<br>                }<br>                else break;<br>            }<br><br>            int roomId = getAvailableRoom(isFree);<br><br>            if (roomId != -1) {<br>                // Room is available<br>                isFree[roomId] = false;<br>                roomIdWithCount[roomId] ++;<br>                endTimeWithRoomId.insert({end+1, roomId});<br>            } else {<br>                auto [freetime, roomNumber] = *endTimeWithRoomId.begin();<br>                endTimeWithRoomId.erase(endTimeWithRoomId.begin());<br><br>                // delay happen<br>                long newStart = freetime;<br>                long newEnd = freetime + (end - start);<br><br>                isFree[roomNumber] = false;<br>                roomIdWithCount[roomNumber] ++;<br>                endTimeWithRoomId.insert({newEnd+1, roomNumber});<br>            }<br>        }<br><br>        int roomWithMaxMeeting = -1, maxMeeting = -1;<br><br>        for (int room = 0; room &lt; n; room ++) {<br>            if (roomIdWithCount[room] &gt; maxMeeting) {<br>                maxMeeting = roomIdWithCount[room];<br>                roomWithMaxMeeting = room;<br>            }<br>        }<br><br>        return roomWithMaxMeeting;<br>    }<br>};</pre><h3>⏱️ Complexity Analysis</h3><ul><li><strong>Time:</strong> O(M log N)<br> (M meetings, ordered insert/remove)</li><li><strong>Space:</strong> O(N + M)</li></ul><p>Efficient and scalable.</p><h3>🧩 Why This Problem Is Important</h3><p>This problem mirrors:</p><ul><li>thread scheduling</li><li>resource pooling</li><li>job queues</li><li>distributed task execution</li></ul><p>If you can solve this cleanly, you’re thinking like:</p><blockquote><em>a backend engineer — not just a competitive programmer.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a574ec1ce6a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Ghost” in the Machine: Why Your API Gateway Requests Are Hanging Indefinitely ]]></title>
            <link>https://medium.com/@vedantrathore627/the-ghost-in-the-machine-why-your-api-gateway-requests-are-hanging-indefinitely-53e3c913d8bc?source=rss-ad88990b5c59------2</link>
            <guid isPermaLink="false">https://medium.com/p/53e3c913d8bc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Vedant Rathore]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 10:14:38 GMT</pubDate>
            <atom:updated>2025-12-26T10:14:38.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhltaTfujGBT_Al0DdcPSA.jpeg" /></figure><p>A debugging story about HTTP headers, Microservices, and the “Content-Length” trap that every developer falls into once.</p><p><strong>Picture this:</strong> You are building a shiny new Microservices architecture. You have a Gateway service that acts as the bouncer — it checks credentials, maybe injects a tenantId or companyId into the request body for security, and then forwards the request to your internal services.</p><p>Everything works perfectly on your local machine. You deploy to the dev environment. You fire a request.</p><p><strong>Loading…</strong> <strong>Loading…</strong> <strong>Loading…</strong></p><p>Eventually: 504 Gateway Timeout.</p><p>No error logs in the internal service. No crash reports. The request just… vanished. It’s a Ghost Request. 👻</p><p>I recently ran into this exact issue. It took hours to debug, but the root cause was so simple (and so fundamental to how the web works) that I knew I had to share it.</p><p>Here is the story of the <strong>Content-Length Trap.</strong></p><h3>The Setup: The “Innocent” Middleware</h3><p>Let’s look at the architecture. We have a standard flow:</p><ul><li><strong>Client</strong> sends a request (e.g., POST /users).</li><li><strong>API Gateway</strong> intercepts it.</li><li><strong>Gateway Logic:</strong> It reads the body, adds a where: { companyId: 101 } clause to ensure the user only accesses their own data.</li><li><strong>Forwarding:</strong> The Gateway uses a library like <strong>Axios</strong> to send this modified request to the downstream User Service.</li></ul><h3>The Mystery of the Hanging Request 🕵️‍♂️</h3><p>When the client sent the original request, the browser (or Postman) calculated the size of the JSON body and attached a header:</p><p>Content-Length: 50 (bytes)</p><p>However, inside our Gateway, we modified the body. We added { &quot;companyId&quot;: 101 }. The <em>actual</em> size of our payload is now, say, <strong>75 bytes</strong>.</p><p>But, because we did headers: req.headers, we are forwarding the <strong>old header</strong>.</p><p>We are sending the downstream service a package that weighs <strong>75 bytes</strong>, but we are slapping a shipping label on it that says <strong>“This package weighs 50 bytes.”</strong></p><h3>Why Axios (and Node.js) get confused</h3><p>HTTP libraries are obedient. They trust the contract defined by the headers.</p><p>When the downstream service receives the request:</p><ol><li>It looks at Content-Length: 50.</li><li>It starts reading the stream of data coming in.</li><li>It reads 50 bytes.</li><li><strong>It stops.</strong></li></ol><p>Wait, what about the other 25 bytes? The { &quot;companyId&quot;: 101 } part?</p><p>Depending on your server configuration (Express, Fastify, Nginx) and your HTTP client (Axios, Fetch), one of two things usually happens:</p><ol><li><strong>Truncation:</strong> The server cuts off the JSON at byte 50, resulting in valid but incomplete JSON (Syntax Error) or missing fields.</li><li><strong>The Hang (The Ghost):</strong> The underlying socket connection gets confused. The client (Gateway) is trying to push 75 bytes. The server says “I’m full at 50.” The stream doesn’t close properly, the promise never resolves, and the connection hangs open until it hits a hard timeout.</li></ol><h3>The Fix: Don’t Lie to your Services</h3><p>The solution is incredibly simple, but easily overlooked. If you touch the body of a request, the old Content-Length is garbage. <strong>Delete it.</strong></p><p>Let the HTTP client (Axios) recalculate the new size automatically.</p><p>In a Microservices architecture, the Gateway acts as a proxy. When you act as a proxy, you have to decide: <strong>Are you a Tunnel or a Transformer?</strong></p><p><strong>Tunnel:</strong> You pass data through exactly as is. (Safe to copy headers).</p><p><strong>Transformer:</strong> You modify data. (UNSAFE to copy headers blindly).</p><p>Whenever you modify the payload, you break the integrity of the original request’s metadata. Always clean up your headers before forwarding.</p><p>Have you ever spent hours debugging a ghost bug only to find out it was a single line of config? Let me know in the comments! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53e3c913d8bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>