<?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 gandharv dalal on Medium]]></title>
        <description><![CDATA[Stories by gandharv dalal on Medium]]></description>
        <link>https://medium.com/@gandharvdalal24?source=rss-6c3d3f075b72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ExtMHdeya7_UyVA8</url>
            <title>Stories by gandharv dalal on Medium</title>
            <link>https://medium.com/@gandharvdalal24?source=rss-6c3d3f075b72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:27:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gandharvdalal24/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[Java Notes -2]]></title>
            <link>https://medium.com/@gandharvdalal24/java-notes-2-927fb7a617c4?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/927fb7a617c4</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 10:15:23 GMT</pubDate>
            <atom:updated>2026-11-28T10:15:23.467Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Question 1 :- What are JDK, JRE, and JVM?</strong></h3><p>JVM (Java Virtual Machine): Runs Java bytecode. It also handles tasks such as memory management and garbage collection. JVM implementations are platform-specific.</p><p>JRE (Java Runtime Environment): The components needed to run Java applications: the JVM plus runtime libraries and other files.</p><p>JDK (Java Development Kit): The tools needed to develop Java applications, such as the compiler (javac), plus the runtime.</p><p>Relationship: The JDK includes the runtime, and the runtime includes the JVM. In simplified terms: JDK → JRE → JVM.</p><pre>JDK: tools to build and run Java programs<br> └── Runtime: libraries and files needed to run them<br>      └── JVM: executes the compiled Java bytecode</pre><p>For example, suppose you write this file:</p><pre>// Hello.java<br>class Hello {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello!&quot;);<br>    }<br>}</pre><ol><li><strong>JDK compiles it:</strong> Run javac Hello.java. The Java compiler creates Hello.class, which contains bytecode.</li><li><strong>JVM runs it:</strong> Run java Hello. The JVM executes the bytecode and prints Hello!.</li><li><strong>JRE provides runtime support:</strong> It includes the JVM and Java libraries the program may need while running.</li></ol><p>So, you need the <strong>JDK</strong> to write and compile Java programs. To run a compiled Java program, you need a Java runtime with a <strong>JVM</strong>.</p><pre><br>You could say:<br><br>- **JDK:** Tools for developing Java programs. It includes the compiler, which converts Java source code (`.java`) into bytecode (`.class`).<br>- **JRE:** The runtime components needed to run Java programs, including the JVM and Java libraries.<br>- **JVM:** Executes the bytecode.<br><br>**Flow:** Write Java code → JDK compiler creates bytecode → JVM runs it using the runtime libraries.</pre><h3><strong>Question 2 : How does Java code execute from a </strong><strong>.java file to machine instructions?</strong></h3><p>Java execution happens in two main stages: <strong>compilation</strong> and <strong>runtime</strong>.</p><p>Suppose you have Hello.java:</p><pre>class Hello {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello!&quot;);<br>    }<br>}</pre><ol><li><strong>Compile:</strong> The JDK compiler (javac) converts the source code into bytecode:</li></ol><pre>javac Hello.java</pre><p>This creates Hello.class. Bytecode is designed for the JVM, rather than for one specific processor.</p><p><strong>2. Load and verify:</strong> When you run:</p><pre>java Hello</pre><p>the JVM loads the class and checks that its bytecode is valid.</p><p><strong>3. Execute:</strong> The JVM begins running the bytecode. It can interpret instructions, and its <strong>JIT compiler</strong> can compile frequently used code into native machine instructions for the current processor.</p><p><strong>4. Run on the processor:</strong> The processor executes those native instructions. The JVM also works with Java runtime libraries — for example, to print Hello!.</p><p>In short:</p><pre>Hello.java → javac → Hello.class (bytecode) → JVM → native machine instructions → processor</pre><p>The JVM may interpret some bytecode and JIT-compile frequently used parts; it doesn’t necessarily convert the entire program to machine instructions all at once.</p><h3>Question 3 : What are Java’s primitive types?</h3><pre>| Type | What it stores | Example |<br>|---|---|---|<br>| `byte` | Small whole numbers | `byte age = 25;` |<br>| `short` | Whole numbers | `short year = 2026;` |<br>| `int` | Whole numbers; commonly used for integer values | `int count = 100;` |<br>| `long` | Large whole numbers | `long population = 8_000_000_000L;` |<br>| `float` | Decimal numbers with less precision | `float price = 9.99f;` |<br>| `double` | Decimal numbers with more precision; commonly used for decimal values | `double pi = 3.14159;` |<br>| `char` | A single UTF-16 code unit | `char grade = &#39;A&#39;;` |<br>| `boolean` | `true` or `false` | `boolean isReady = true;` |</pre><h3>Question 4 : What is the difference between a primitive and a reference type?</h3><p>A <strong>primitive type</strong> stores a simple value directly. A <strong>reference type</strong> stores a reference to an object.</p><pre>int age = 25;                 // primitive: stores the number 25<br>String name = &quot;Gandharv&quot;;      // reference: refers to a String object</pre><h3>Question 5 : Can a constructor be private? When might you use one?</h3><p>Yes. A constructor can be private, which prevents other classes from creating instances with new.</p><p>Here are examples of each use case.</p><h3>1. Singleton — one shared instance</h3><pre>final class AppConfig {<br>    private static final AppConfig INSTANCE = new AppConfig();<br>    private AppConfig() {}<br>    public static AppConfig getInstance() {<br>        return INSTANCE;<br>    }<br>}<br>// Usage<br>AppConfig config = AppConfig.getInstance();</pre><p>The private constructor prevents other classes from calling new AppConfig(). getInstance() returns the shared instance.</p><h3>2. Utility class — methods that don’t need an object</h3><pre>final class MathUtils {<br>    private MathUtils() {}<br>    public static int square(int number) {<br>            return number * number;<br>        }<br>    }<br>    // Usage<br>    int result = MathUtils.square(5); // 25</pre><p>The private constructor prevents unnecessary objects such as new MathUtils().</p><h3>3. Factory method — control how objects are created</h3><pre>class Notification {<br>    private final String channel;<br>    private Notification(String channel) {<br>        this.channel = channel;<br>    }<br>    public static Notification create(String channel) {<br>        if (!channel.equals(&quot;email&quot;) &amp;&amp; !channel.equals(&quot;sms&quot;)) {<br>            throw new IllegalArgumentException(&quot;Unsupported channel&quot;);<br>        }<br>        return new Notification(channel);<br>    }<br>    public String getChannel() {<br>        return channel;<br>    }<br>}<br>// Usage<br>Notification notification = Notification.create(&quot;email&quot;);</pre><p>The private constructor makes create() the controlled way to create a Notification. It can validate input or choose which object to return.</p><h3>Question 6 : Can static methods be overridden?</h3><p>No. <strong>Static methods are not overridden</strong> in Java because they belong to the class, not to an instance. If a subclass declares a static method with the same signature, it <strong>hides</strong> the parent method.</p><pre>class Parent {<br>    static void show() {<br>        System.out.println(&quot;Parent&quot;);<br>    }<br>}<br>class Child extends Parent {<br>    static void show() {<br>        System.out.println(&quot;Child&quot;); // hides Parent.show()<br>    }<br>}<br>Parent item = new Child();<br>item.show(); // Prints &quot;Parent&quot;<br>Child.show(); // Prints &quot;Child&quot;</pre><pre>The method called is chosen using the <strong>reference’s declared type</strong> (Parent or Child), not the object’s runtime type. Instance methods behave differently: they can be overridden, and the runtime object determines which version runs.</pre><h3>Question 7 : Can private or final methods be overridden?</h3><p><strong>private methods:</strong> They cannot be overridden because they aren’t visible to subclasses. A subclass can declare a method with the same name and signature, but it’s a separate method.</p><pre>class Parent {<br>    private void show() {<br>        System.out.println(&quot;Parent&quot;);<br>    }<br>}<br><br>class Child extends Parent {<br>    void show() { // A new method, not an override<br>        System.out.println(&quot;Child&quot;);<br>    }<br>}</pre><p><strong>final methods:</strong> They cannot be overridden. A subclass cannot provide a new implementation with the same signature.</p><pre>class Parent {<br>    final void show() {<br>        System.out.println(&quot;Parent&quot;);<br>    }<br>}<br><br>class Child extends Parent {<br>    // void show() {} // Compile error: cannot override a final method<br>}</pre><h3>Question 8 : What is the difference between an abstract class and an interface?</h3><p>An <strong>abstract class</strong> and an <strong>interface</strong> both define behavior that subclasses can implement, but they serve different purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*TVfnSCVQDRpRQJ_1IO7kwg.png" /></figure><p><strong>Example:</strong> An abstract class can hold shared state and implementation:</p><pre>abstract class Animal {<br>    protected String name;<br><br>    Animal(String name) {<br>        this.name = name;<br>    }<br><br>    abstract void makeSound();<br><br>    void sleep() {<br>        System.out.println(name + &quot; is sleeping&quot;);<br>    }<br>}<br><br>class Dog extends Animal {<br>    Dog(String name) {<br>        super(name);<br>    }<br><br>    @Override<br>    void makeSound() {<br>        System.out.println(&quot;Bark&quot;);<br>    }<br>}</pre><p>An interface describes a capability that different classes can provide:</p><pre>interface Flyable {<br>    void fly();<br>}<br><br>class Bird implements Flyable {<br>    @Override<br>    public void fly() {<br>        System.out.println(&quot;Bird is flying&quot;);<br>    }<br>}</pre><p>Use an <strong>abstract class</strong> when related classes need shared state or implementation. Use an <strong>interface</strong> when you want to define a capability that different classes can implement.</p><h3>Question 9 : Can an interface have default, static, and private methods?</h3><p>Yes. Modern Java interfaces can have all three:</p><ul><li><strong>default methods</strong> provide an instance method implementation that implementing classes inherit. A class can override it.</li><li><strong>static methods</strong> belong to the interface and are called using the interface name.</li><li><strong>private methods</strong> are helper methods used inside the interface, often to share code between its default methods. They aren’t inherited or called directly by implementing classes.</li></ul><pre>interface Greeting {<br>    default void sayHello(String name) {<br>        printMessage(&quot;Hello, &quot; + name);<br>    }<br><br>    static String language() {<br>        return &quot;English&quot;;<br>    }<br><br>    private void printMessage(String message) {<br>        System.out.println(message);<br>    }<br>}<br><br>class Person implements Greeting {}<br><br>Person person = new Person();<br>person.sayHello(&quot;Sam&quot;);                    // Hello, Sam<br>System.out.println(Greeting.language());   // English</pre><p>Private interface methods require <strong>Java 9 or later</strong>.</p><p>Imp :-</p><pre>class Employee {<br>    private String id;       // only inside Employee<br>    String department;       // package-private<br>    protected double salary; // package and subclasses<br>    public String name;      // everywhere the class is accessible<br>}</pre><p>A <strong>package</strong> in Java is a way to group related classes and interfaces under a name. It helps organize code and avoid name conflicts.</p><p>For example:</p><pre>package com.example.shop;<br><br>public class Product {<br>}</pre><pre>This declares Product as part of the com.example.shop package. Another class can use it with an import:</pre><pre>import com.example.shop.Product;<br><br>class Cart {<br>    Product item;<br>}</pre><p>Packages also affect access: members with <strong>no access modifier</strong> (package-private) can be used by classes in the <strong>same package</strong>, but not by unrelated classes in another package.</p><h3>Question 10 :- What is an enum, and when is it useful?</h3><p>An <strong>enum</strong> is a Java type that represents a fixed set of named values. Use one when a variable should only have a known set of choices.</p><pre>enum OrderStatus {<br>    PENDING,<br>    SHIPPED,<br>    DELIVERED,<br>    CANCELLED<br>}</pre><p>You can use it like this:</p><pre>OrderStatus status = OrderStatus.SHIPPED;<br><br>if (status == OrderStatus.SHIPPED) {<br>    System.out.println(&quot;Your order is on its way.&quot;);<br>}</pre><p>Enums are useful for things like order status, days of the week, directions, or user roles. They’re safer than strings because the compiler can catch invalid values — for example, &quot;SHIPED&quot; would be a typo, while OrderStatus.SHIPED causes a compile error.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=927fb7a617c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi Threading]]></title>
            <link>https://medium.com/@gandharvdalal24/multi-threading-cfd15c0e1ea7?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfd15c0e1ea7</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 08:55:56 GMT</pubDate>
            <atom:updated>2026-11-28T08:55:56.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>9. Process vs. thread</h3><p>A <strong>process</strong> is a running program with its own memory space and resources.</p><p>A <strong>thread</strong> is a path of execution inside a process. Threads in the same process share the heap, but each thread has its own stack and execution state.</p><p>Multiple threads can improve responsiveness or handle independent work concurrently. Because they share data, they can also introduce race conditions.</p><h3>Creating and running tasks</h3><p>You can define a task with Runnable and run it on a thread:</p><pre>Runnable task = () -&gt; System.out.println(&quot;Running on a thread&quot;);</pre><pre>Thread thread = new Thread(task);<br>thread.start(); // Starts a new thread</pre><p>Calling thread.run() directly does <strong>not</strong> start a new thread; it just calls the method on the current thread.</p><p>In most application code, prefer ExecutorService to managing raw threads yourself.</p><h3>10. Thread lifecycle</h3><p>Java’s Thread.State values are:</p><ul><li><strong>NEW:</strong> created but not started.</li><li><strong>RUNNABLE:</strong> eligible to run or currently running.</li><li><strong>BLOCKED:</strong> waiting to acquire a monitor lock.</li><li><strong>WAITING:</strong> waiting indefinitely for another action, such as notification or thread completion.</li><li><strong>TIMED_WAITING:</strong> waiting for a limited time, such as during sleep() or timed join().</li><li><strong>TERMINATED:</strong> finished execution.</li></ul><p>These are JVM states; RUNNABLE includes both “ready to run” and “currently running.”</p><p>These are the states returned by Java’s Thread.getState(). A thread moves between states as your program starts it, makes it wait, and lets it finish.</p><h3>Example</h3><pre>class Worker extends Thread {<br>    private final Object lock;</pre><pre>    Worker(Object lock) {<br>        this.lock = lock;<br>    }</pre><pre>    @Override<br>    public void run() {<br>        synchronized (lock) {<br>            try {<br>                Thread.sleep(500); // TIMED_WAITING<br>            } catch (InterruptedException e) {<br>                Thread.currentThread().interrupt();<br>            }<br>        }<br>    }<br>}</pre><pre>public class ThreadStatesDemo {<br>    public static void main(String[] args) throws InterruptedException {<br>        Object lock = new Object();</pre><pre>        Worker worker = new Worker(lock);</pre><pre>        System.out.println(worker.getState()); // NEW</pre><pre>        synchronized (lock) {<br>            worker.start();</pre><pre>            Thread.sleep(100); // Give worker time to try to acquire lock<br>            System.out.println(worker.getState()); // BLOCKED</pre><pre>            // The main thread releases lock when it exits this block<br>        }</pre><pre>        Thread.sleep(100); // Worker can acquire lock and call sleep()<br>        System.out.println(worker.getState()); // TIMED_WAITING</pre><pre>        worker.join(); // Main waits until worker finishes<br>        System.out.println(worker.getState()); // TERMINATED<br>    }<br>}</pre><p>The printed states are timing-dependent, so this demo illustrates the transitions; it is not a reliable way to test them.</p><h3>What happens</h3><ol><li><strong>NEW</strong> — worker has been created, but start() hasn’t been called.</li><li><strong>BLOCKED</strong> — the main thread holds lock. The worker has started and is trying to enter synchronized (lock), so it must wait for the monitor lock.</li><li><strong>TIMED_WAITING</strong> — after acquiring the lock, the worker calls sleep(500). It waits for a limited time.</li><li><strong>TERMINATED</strong> — run() finishes.</li></ol><h3>The other states</h3><ul><li><strong>RUNNABLE</strong> — after start(), the thread is eligible to run or is running. Java does not expose a separate RUNNING state.</li><li><strong>WAITING</strong> — the thread waits until another action happens. For example, join() with no timeout makes the <strong>calling thread</strong> wait for the thread it joined.</li></ul><pre>worker.join(); // The thread calling this waits until worker finishes</pre><ul><li><strong>TIMED_WAITING</strong> — the thread waits for a duration, such as with sleep(500) or join(500).</li></ul><p>One distinction: sleep() does <strong>not</strong> release a monitor lock the thread already holds. In the example, the worker keeps lock while sleeping, then releases it when it exits the synchronized block.</p><h3>11. Concurrency, parallelism, and race conditions</h3><p>Think of <strong>concurrency</strong> as tasks taking turns, <strong>parallelism</strong> as tasks running at the same time, and a <strong>race condition</strong> as an incorrect result caused by overlapping access to shared data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFalEu5mQxPNrhHm9kXdeA.png" /></figure><p>With one core, the processor switches between tasks, so both make progress over the same period. With multiple cores, tasks can actually run at the same time.</p><h3>How a race condition loses an update</h3><p>Suppose two threads run count++ when count is 0. Each increment is really <strong>read → add → write</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTD5njVkERWEefLq2DIXSw.png" /></figure><p>Both threads read the same old value, so one increment gets lost. That’s a <strong>race condition</strong>. Protect shared updates with synchronized, a lock, or an atomic type such as AtomicInteger.</p><p><strong>Concurrency vs. parallelism</strong></p><p><strong>Concurrency</strong> means multiple tasks make progress during overlapping periods. They may take turns on one core.</p><p><strong>Parallelism</strong> means multiple tasks are executing at the same time, typically on multiple cores.</p><p>A <strong>race condition</strong> happens when the result depends on the timing or order of threads accessing shared data.</p><pre>class Counter {<br>    int count = 0;</pre><pre>void increment() {<br>        count++; // Not one indivisible operation<br>    }<br>}</pre><p>If two threads call increment() at the same time, both may read the same old value and overwrite each other’s update. The final count can be too low.</p><p>Protect shared state with synchronization, a lock, or an atomic class:</p><pre>import java.util.concurrent.atomic.AtomicInteger;</pre><pre>AtomicInteger count = new AtomicInteger();<br>count.incrementAndGet();</pre><h3>12. synchronized vs. volatile</h3><h3>synchronized</h3><p>A synchronized method or block provides:</p><ol><li><strong>Mutual exclusion:</strong> only one thread at a time can hold the same monitor lock.</li><li><strong>Visibility:</strong> changes made before releasing the lock become visible to a thread that later acquires that lock.</li></ol><pre>class Counter {<br>    private int count;</pre><pre>synchronized void increment() {<br>        count++;<br>    }</pre><pre>synchronized int getCount() {<br>        return count;<br>    }<br>}</pre><h3>volatile</h3><p>A volatile field ensures that reads and writes go to a value visible across threads. It is useful for simple status flags.</p><pre>class Worker {<br>    private volatile boolean running = true;</pre><pre>void stop() {<br>        running = false;<br>    }</pre><pre>void work() {<br>        while (running) {<br>            // Do work<br>        }<br>    }<br>}</pre><p>volatile <strong>does not</strong> make compound operations atomic. For example, count++ is still a read-modify-write sequence and can lose updates if multiple threads do it concurrently.</p><p><strong>Shortcut:</strong> Use volatile for visibility of a simple value; use synchronization or atomic classes when you need safe updates or coordination.</p><h3>13. Intrinsic locks and synchronized blocks</h3><p>Every Java object can act as a monitor lock. A synchronized instance method locks the current object (this). A static synchronized method locks the Class object.</p><p>A synchronized block lets you choose the lock and narrow the locked section:</p><pre>class Counter {<br>    private int count = 0;<br>    private final Object lock = new Object();</pre><pre>void increment() {<br>        synchronized (lock) {<br>            count++;<br>        }<br>    }<br>}</pre><p>Threads that synchronize using the <strong>same lock object</strong> coordinate with each other. Locking different objects does not protect the same shared state.</p><h3>14. wait() vs. sleep(); notify() vs. notifyAll()</h3><h3>wait()</h3><ul><li>Must be called while holding the same object’s monitor, usually inside synchronized.</li><li>Releases that monitor while waiting.</li><li>Resumes after notification or interruption, then must reacquire the monitor.</li></ul><h3>sleep()</h3><ul><li>Pauses the current thread for a duration.</li><li>Does <strong>not</strong> release locks the thread already holds.</li><li>Does not require a synchronized block.</li></ul><h3>notify() and notifyAll()</h3><ul><li>Must be called while holding that object’s monitor.</li><li>notify() wakes one waiting thread; notifyAll() wakes all threads waiting on that monitor.</li><li>A notified thread still needs to reacquire the lock before continuing.</li></ul><p>Wait conditions should be checked in a loop because a thread can wake up even if the condition is not satisfied:</p><pre>synchronized (lock) {<br>    while (!ready) {<br>        lock.wait();<br>    }<br>    // Continue when ready is true<br>}</pre><h3>15. join() and interruption</h3><p>join() lets one thread wait for another thread to finish:</p><pre>Thread worker = new Thread(() -&gt; doWork());<br>worker.start();</pre><pre>worker.join(); // Current thread waits for worker to finish</pre><p><strong>Interruption</strong> is a cooperative way to request that a thread stop waiting or cancel work. Methods such as sleep(), wait(), and join() can throw InterruptedException.</p><p>Don’t silently ignore interruption. If you cannot propagate the exception, restore the interrupt flag:</p><pre>try {<br>    Thread.sleep(1000);<br>} catch (InterruptedException e) {<br>    Thread.currentThread().interrupt();<br>    return;<br>}</pre><p>Interruption is a signal; the task’s code should respond to it and clean up as needed.</p><h3>16. Deadlock, starvation, and livelock</h3><h3>Deadlock</h3><p>Two or more threads wait forever for locks held by one another.</p><p>Example: Thread A holds lock 1 and waits for lock 2; Thread B holds lock 2 and waits for lock 1.</p><p><strong>Prevention:</strong></p><ul><li>Acquire locks in a consistent global order.</li><li>Avoid holding one lock while waiting for another.</li><li>Use timed lock attempts, such as tryLock(), where appropriate.</li><li>Keep critical sections short.</li></ul><h3>Starvation</h3><p>A thread waits indefinitely because other threads repeatedly get the resource or lock first.</p><p><strong>Prevention:</strong> Reduce unfair contention, keep lock holds short, and use fair locks when fairness is more important than throughput.</p><h3>Livelock</h3><p>Threads remain active and keep responding to one another, but fail to make progress — for example, each repeatedly backs off to let the other proceed.</p><p><strong>Prevention:</strong> Add randomized backoff or change the coordination strategy so both threads do not keep making the same response.</p><h3>17. Thread safety</h3><p>A class is <strong>thread-safe</strong> when it behaves correctly when multiple threads use it at the same time.</p><p>Common ways to achieve thread safety:</p><ul><li>Avoid shared mutable state.</li><li>Use immutable objects.</li><li>Protect shared state with synchronized blocks or locks.</li><li>Use atomic classes such as AtomicInteger.</li><li>Use concurrent collections such as ConcurrentHashMap.</li><li>Confine data to one thread where possible.</li></ul><p>A collection being thread-safe does not automatically make a sequence of multiple collection operations atomic. Choose an operation designed for the whole action or add appropriate coordination.</p><h3>18. ExecutorService and thread pools</h3><p>An ExecutorService manages task execution so application code can submit tasks without manually creating a new thread for each one.</p><p>A <strong>thread pool</strong> reuses a set of worker threads. This reduces thread creation overhead and helps control how many tasks run at once.</p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;</pre><pre>ExecutorService executor = Executors.newFixedThreadPool(4);</pre><pre>executor.submit(() -&gt; {<br>    System.out.println(&quot;Task running&quot;);<br>});</pre><pre>executor.shutdown(); // Stop accepting new tasks; finish submitted tasks</pre><p>In production, choose the pool size and queue policy based on the workload. An unbounded queue or excessive thread count can cause resource problems. Always shut down a pool when its owner is finished with it.</p><h3>Runnable vs. Callable</h3><ul><li>Runnable runs a task without returning a result.</li><li>Callable&lt;T&gt; returns a result and can throw a checked exception.</li></ul><pre>Future&lt;Integer&gt; result = executor.submit(() -&gt; 10 + 20);<br>System.out.println(result.get()); // 30; waits if needed</pre><p>Future.get() can block. For asynchronous composition, Java also provides CompletableFuture.</p><h3>19. Locks and atomic classes</h3><p>The Lock API offers explicit locking. ReentrantLock supports features such as timed lock attempts and optional fairness.</p><pre>import java.util.concurrent.locks.ReentrantLock;</pre><pre>class Counter {<br>    private final ReentrantLock lock = new ReentrantLock();<br>    private int count;</pre><pre>void increment() {<br>        lock.lock();<br>        try {<br>            count++;<br>        } finally {<br>            lock.unlock();<br>        }<br>    }<br>}</pre><p>Always unlock in finally.</p><p>Atomic classes such as AtomicInteger provide thread-safe operations for single values without writing a synchronized block:</p><pre>AtomicInteger counter = new AtomicInteger();<br>counter.incrementAndGet();</pre><h3>20. Daemon threads</h3><p>A daemon thread is a background service thread. The JVM can exit when only daemon threads remain.</p><pre>Thread background = new Thread(() -&gt; runBackgroundTask());<br>background.setDaemon(true); // Set before start()<br>background.start();</pre><p>Use daemon threads for background support work, not for tasks that must complete before shutdown; the JVM does not wait for them.</p><h3>21. Lambda expressions, functional interfaces, and Streams</h3><p>A <strong>lambda</strong> is a concise way to provide behavior, often for a functional interface.</p><p>A <strong>functional interface</strong> has exactly one abstract method. Examples include Runnable, Callable, and Predicate&lt;T&gt;.</p><pre>Runnable task = () -&gt; System.out.println(&quot;Hello from a task&quot;);</pre><p>A <strong>Stream</strong> processes a sequence of values through operations such as filter, map, and collect. A stream is not a collection; it does not store the data itself.</p><pre>List&lt;String&gt; names = List.of(&quot;Asha&quot;, &quot;Ravi&quot;, &quot;Anita&quot;);</pre><pre>List&lt;String&gt; result = names.stream()<br>        .filter(name -&gt; name.startsWith(&quot;A&quot;))<br>        .map(String::toUpperCase)<br>        .toList();</pre><pre>System.out.println(result); // [ASHA, ANITA]</pre><p>Streams are usually best for expressing data transformations. Avoid side effects inside stream operations, especially parallel streams.</p><h3>22. map() vs. flatMap()</h3><ul><li>map() transforms each input into one output.</li><li>flatMap() transforms each input into a stream or container, then flattens the results into one stream.</li></ul><pre>List&lt;String&gt; names = List.of(&quot;Asha&quot;, &quot;Ravi&quot;);</pre><pre>List&lt;Integer&gt; lengths = names.stream()<br>        .map(String::length)<br>        .toList();<br>// [4, 4]</pre><p>Example of flatMap():</p><pre>List&lt;List&lt;String&gt;&gt; teams = List.of(<br>        List.of(&quot;Asha&quot;, &quot;Ravi&quot;),<br>        List.of(&quot;Anita&quot;, &quot;Dev&quot;)<br>);</pre><pre>List&lt;String&gt; allNames = teams.stream()<br>        .flatMap(List::stream)<br>        .toList();<br>// [Asha, Ravi, Anita, Dev]</pre><h3>23. Intermediate vs. terminal stream operations</h3><p><strong>Intermediate operations</strong> return another stream and are generally lazy. Examples: filter(), map(), sorted().</p><p><strong>Terminal operations</strong> produce a result or side effect and trigger processing. Examples: toList(), collect(), count(), forEach(), reduce().</p><pre>long count = names.stream()      // Stream begins<br>        .filter(n -&gt; n.startsWith(&quot;A&quot;)) // Intermediate<br>        .count();                 // Terminal: triggers processing</pre><p>A stream should generally be used once; create a new stream from the source for another pipeline.</p><h3>24. Optional</h3><p>Optional&lt;T&gt; represents a value that may or may not be present. It can make a missing return value explicit and help avoid some null checks.</p><pre>Optional&lt;String&gt; name = Optional.ofNullable(findName());</pre><pre>String displayName = name.orElse(&quot;Unknown&quot;);</pre><p>Common methods:</p><ul><li>isPresent() / isEmpty() — check whether a value exists.</li><li>orElse(value) — return a fallback value.</li><li>orElseGet(supplier) — compute a fallback only when needed.</li><li>orElseThrow() — throw if empty.</li><li>map() — transform a present value.</li></ul><p>Prefer using Optional as a return type when absence is meaningful. It is usually not needed for every field or method parameter.</p><h3>Quick multithreading revision</h3><ul><li><strong>Race condition:</strong> result changes depending on thread timing.</li><li><strong>synchronized:</strong> mutual exclusion plus visibility for code using the same monitor.</li><li><strong>volatile:</strong> visibility for a field; not atomicity for compound operations.</li><li><strong>wait():</strong> releases the monitor while waiting; sleep() keeps held locks.</li><li><strong>Deadlock:</strong> threads wait on each other’s locks indefinitely.</li><li><strong>Thread pool:</strong> reuses threads and controls task execution.</li><li><strong>AtomicInteger:</strong> thread-safe operations on a single integer.</li><li><strong>ConcurrentHashMap:</strong> map designed for concurrent access.</li><li><strong>Interruption:</strong> cooperative cancellation signal; preserve the interrupt status if you catch and cannot propagate it.</li></ul><h3>Progress</h3><p>You’ve covered these <strong>16 requested areas</strong>. The broad multithreading section is now organized around the core interview concepts: thread lifecycle, synchronization, coordination, safety, cancellation, and task execution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfd15c0e1ea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graphs]]></title>
            <link>https://medium.com/@gandharvdalal24/graphs-1103b89e9e48?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/1103b89e9e48</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 12:23:30 GMT</pubDate>
            <atom:updated>2026-11-16T12:23:30.711Z</atom:updated>
            <content:encoded><![CDATA[<p>topological sort:-</p><pre>private List&lt;List&lt;Integer&gt;&gt; createGraph(int size) {<br>        List&lt;List&lt;Integer&gt;&gt; graph = new ArrayList&lt;&gt;();<br>        for (int i = 0; i &lt; size; i++) {<br>            graph.add(new ArrayList&lt;&gt;());<br>        }<br>        return graph;<br>    }<br><br>    private List&lt;Integer&gt; topologicalSort(List&lt;List&lt;Integer&gt;&gt; graph,<br>                                          int[] indegree) {<br>        Queue&lt;Integer&gt; queue = new LinkedList&lt;&gt;();<br><br>        for (int i = 0; i &lt; indegree.length; i++) {<br>            if (indegree[i] == 0) {<br>                queue.offer(i);<br>            }<br>        }<br><br>        List&lt;Integer&gt; order = new ArrayList&lt;&gt;();<br><br>        while (!queue.isEmpty()) {<br>            int current = queue.poll();<br>            order.add(current);<br><br>            for (int next : graph.get(current)) {<br>                indegree[next]--;<br>                if (indegree[next] == 0) {<br>                    queue.offer(next);<br>                }<br>            }<br>        }<br><br>        return order;<br>    }</pre><p><strong>Kahn’s algorithm, a BFS-based topological sort:-<br>To detect cycle in directed graph:-</strong></p><pre>Kahn’s algorithm is a **BFS method for topological sorting**. For Course Schedule, it helps us check whether all courses can be completed.<br><br>Let’s use this example:<br><br>```text<br>numCourses = 4<br>prerequisites = [[1,0], [2,0], [3,1], [3,2]]<br>```<br><br>`[course, prerequisite]` means **take the prerequisite first**. So the arrows are:<br><br>```text<br>0 → 1 → 3<br> \       ↑<br>  → 2 ───┘<br>```<br><br>Course `0` comes first. Courses `1` and `2` both require `0`. Course `3` requires both `1` and `2`.<br><br>### Step 1: Count each course’s prerequisites<br><br>This count is called **in-degree**:<br><br>```text<br>Course 0: 0 prerequisites<br>Course 1: 1 prerequisite (0)<br>Course 2: 1 prerequisite (0)<br>Course 3: 2 prerequisites (1 and 2)<br><br>inDegree = [0, 1, 1, 2]<br>```<br><br>Start a queue with courses that have **zero prerequisites**:<br><br>```text<br>Queue: [0]<br>```<br><br>### Step 2: Take a course and unlock the next ones<br><br>Remove `0` from the queue and mark it completed. Since `0` is a prerequisite for `1` and `2`, reduce their in-degree counts:<br><br>```text<br>Before: inDegree = [0, 1, 1, 2]<br>Take 0<br>After:  inDegree = [0, 0, 0, 2]<br><br>Queue: [1, 2]<br>Completed: 1<br>```<br><br>Now `1` and `2` have no remaining prerequisites, so both can be taken.<br><br>Remove `1`. It is a prerequisite for `3`, so decrement `inDegree[3]`:<br><br>```text<br>inDegree[3]: 2 → 1<br>Queue: [2]<br>```<br><br>Remove `2`. It is also a prerequisite for `3`:<br><br>```text<br>inDegree[3]: 1 → 0<br>Queue: [3]<br>```<br><br>Now remove `3`:<br><br>```text<br>Queue: []<br>Completed: 4<br>```<br><br>We completed all `4` courses, so the answer is **`true`**.<br><br>### How this detects a cycle<br><br>If there’s a cycle, none of its courses can reach in-degree `0`:<br><br>```text<br>0 → 1 → 2<br>↑       ↓<br>└───────┘<br>```<br><br>Each course in the cycle is waiting for another course in the same cycle. Kahn’s algorithm can’t remove them from the queue, so `completed &lt; numCourses`. The answer is **`false`**.<br><br>In code, `inDegree[course]--` means: “one prerequisite of this course has now been completed.” When its count reaches `0`, add it to the queue.</pre><pre>class Solution {<br>    public boolean canFinish(int numCourses, int[][] pr) {<br><br>        int indegree[]=new int[numCourses];<br>        ArrayList&lt;ArrayList&lt;Integer&gt;&gt;graph=new ArrayList&lt;&gt;();<br><br>        for(int i=0;i&lt;numCourses;i++){<br>            graph.add(new ArrayList&lt;Integer&gt;());<br>        }<br><br>        for(int arr[]:pr){<br>            indegree[arr[0]]++;<br>            graph.get(arr[1]).add(arr[0]);<br>        }<br><br>        int count=0;<br><br><br>        LinkedList&lt;Integer&gt;queue=new LinkedList&lt;&gt;();<br>        for(int i=0;i&lt;indegree.length;i++){<br>            if(indegree[i]==0){<br>                <br>                queue.add(i);<br>            }<br>        }<br><br><br>        while(queue.size()!=0){<br>        <br>                int temp=queue.remove();<br>                count++;<br>                for(int j=0;j&lt;graph.get(temp).size();j++){<br>                    indegree[graph.get(temp).get(j)]--;<br>                    if( indegree[graph.get(temp).get(j)]==0){<br>                        queue.add( graph.get(temp).get(j));<br>                    }<br>                    <br>                }<br><br><br>      <br>        }<br><br><br>        return count==numCourses?true:false;<br><br><br>        <br>    }<br>}</pre><p><strong><em>Is bipartite</em>.</strong></p><pre>Start node 0: color it Red<br>Every neighbor must be Blue<br>Every neighbor&#39;s neighbor must be Red<br><br><br>Red:   1 —— 2   :Blue<br>       |    |<br>Blue:  4 —— 3<br><br><br><br><br><br>import java.util.*;<br><br>class Solution {<br>    public boolean isBipartite(int[][] graph) {<br>        int[] color = new int[graph.length]; // 0 = uncolored<br><br>        for (int k = 0; k &lt; graph.length; k++) {<br>            if (color[k] != 0) {<br>                continue;<br>            }<br><br>            Queue&lt;Integer&gt; queue = new LinkedList&lt;&gt;();<br>            queue.add(k);<br>            color[k] = 1;<br><br>            while (!queue.isEmpty()) {<br>                int node = queue.remove();<br><br>                for (int neighbor : graph[node]) {<br>                    if (color[neighbor] == 0) {<br>                        // Give the neighbor the opposite color<br>                        color[neighbor] = -color[node];<br>                        queue.add(neighbor);<br>                    } else if (color[neighbor] == color[node]) {<br>                        // An edge connects nodes with the same color<br>                        return false;<br>                    }<br>                }<br>            }<br>        }<br><br>        return true;<br>    }<br>}</pre><p><strong>Disjoint Set Union (DSU) concept :-</strong></p><blockquote>DSU to detect whether two nodes are already connected</blockquote><p>→ detects cycle in undirected graph</p><p>example question :- 684. Redundant Connection</p><pre>Let’s dry run the code on:<br><br>```text<br>edges = [[1,2], [1,3], [2,3]]<br>```<br><br>### 1. Initialize DSU<br><br>At first, every node is its own parent:<br><br>```text<br>parent[1] = 1<br>parent[2] = 2<br>parent[3] = 3<br><br>Groups:  {1}   {2}   {3}<br>```<br><br>`find(x)` follows parent links to return the root of `x`’s group.<br><br>`union(root1, root2)` joins two groups by changing one root’s parent.<br><br>### 2. Process edge `[1,2]`<br><br>```java<br>root1 = find(1); // 1<br>root2 = find(2); // 2<br>```<br><br>Roots differ, so they’re not connected yet. The code calls:<br><br>```java<br>union(parent, rank, 1, 2);<br>```<br><br>Both ranks are equal, so `parent[2] = 1`.<br><br>```text<br>  1<br> /<br>2       3<br><br>Groups:  {1,2}   {3}<br>```<br><br>### 3. Process edge `[1,3]`<br><br>```java<br>root1 = find(1); // 1<br>root2 = find(3); // 3<br>```<br><br>Roots differ, so the code joins those groups. It sets `parent[3] = 1`.<br><br>```text<br>  2<br>  |<br>  1 —— 3<br><br>Groups:  {1,2,3}<br>```<br><br>### 4. Process edge `[2,3]`<br><br>```java<br>root1 = find(2); // 1, because parent[2] is 1<br>root2 = find(3); // 1, because parent[3] is 1<br>```<br><br>The roots match:<br><br>```java<br>if (root1 == root2) {<br>    return edge;<br>}<br>```<br><br>So the method returns:<br><br>```text<br>[2,3]<br>```<br><br>The graph already has a path from `2` to `3` through `1`. Adding `[2,3]` closes the cycle:<br><br>```text<br>2<br>|\<br>| \<br>1——3<br>```<br><br>### Your turn<br><br>For these edges, what does the code return?<br><br>```text<br>edges = [[1,2], [2,3], [3,4], [1,4], [1,5]]<br>```<br><br>Hint: trace the roots for each edge in order.<br><br><br>class Solution {<br>    public int[] findRedundantConnection(int[][] edges) {<br>        int n = edges.length;<br>        int[] parent = new int[n + 1];<br>        int[] rank = new int[n + 1];<br><br>        for (int i = 1; i &lt;= n; i++) {<br>            parent[i] = i;<br>        }<br><br>        for (int[] edge : edges) {<br>            int root1 = find(parent, edge[0]);<br>            int root2 = find(parent, edge[1]);<br><br>            if (root1 == root2) {<br>                return edge;<br>            }<br><br>            union(parent, rank, root1, root2);<br>        }<br><br>        return new int[]{-1, -1};<br>    }<br><br>    private int find(int[] parent, int node) {<br>        if (parent[node] != node) {<br>            parent[node] = find(parent, parent[node]);<br>        }<br>        return parent[node];<br>    }<br><br>    private void union(int[] parent, int[] rank, int root1, int root2) {<br>        if (rank[root1] &lt; rank[root2]) {<br>            parent[root1] = root2;<br>        } else if (rank[root1] &gt; rank[root2]) {<br>            parent[root2] = root1;<br>        } else {<br>            parent[root2] = root1;<br>            rank[root1]++;<br>        }<br>    }<br>}</pre><pre>ideas:-<br>1. In a matrix if we want to disconnect 1 whole island ans would be either 0,1 or 2 max</pre><pre>Integer min priority Queue<br>PriorityQueue&lt;Entity&gt;pq=new PriorityQueue&lt;&gt;((a,b)-&gt;Integer.compare(a.val,b.val));</pre><p>bfs in matrix:-</p><pre>class Solution {<br>    public int orangesRotting(int[][] grid) {<br><br>        int n=grid.length;<br>        int m=grid[0].length;<br><br><br>        boolean visited[][]=new boolean[n][m];<br><br>        LinkedList&lt;int[]&gt;queue=new LinkedList&lt;&gt;();<br><br>        int count=-1;<br><br>        int count_one=0;<br><br><br>        for(int i=0;i&lt;n;i++){<br>            for(int j=0;j&lt;m;j++){<br>                if(grid[i][j]==2){<br>                    queue.addLast(new int[]{i,j});<br>                    visited[i][j]=true;<br>                }<br>                if(grid[i][j]==1){<br>                    count_one++;<br>                }<br>            }<br>        }<br><br><br>        int dir[][]={{-1,0},{1,0},{0,-1},{0,1}};<br><br><br><br><br><br>        while(queue.size()&gt;0){<br>            int size=queue.size();<br>            count++;<br><br><br>            for(int i=0;i&lt;size;i++){<br>                int temp[]=queue.removeFirst();<br><br>                for(int j=0;j&lt;dir.length;j++){<br>                    int nx=temp[0]+dir[j][0];<br>                    int ny=temp[1]+dir[j][1];<br><br>                    if(nx&gt;=0 &amp;&amp; nx&lt;grid.length &amp;&amp; ny&gt;=0 &amp;&amp; ny&lt;grid[0].length &amp;&amp; !visited[nx][ny] &amp;&amp; grid[nx][ny]==1){<br>                        count_one--;<br>                        visited[nx][ny]=true;<br>                        queue.addLast(new int[]{nx,ny});<br>                    }<br>                }<br><br><br><br>            <br><br>            }<br>        }<br><br>        if(count==-1){<br>            count=0;<br>        }<br><br>        return count_one&gt;0?-1:count;<br>        <br>    }<br>}</pre><p>dfs in graph :-</p><pre>class Solution {<br>    public List&lt;List&lt;Integer&gt;&gt; allPathsSourceTarget(int[][] graph) {<br><br>        List&lt;List&lt;Integer&gt;&gt;ans=new ArrayList&lt;&gt;();<br><br>        int visited[]=new int[graph.length];<br><br>        List&lt;Integer&gt;list=new ArrayList&lt;&gt;();<br>        list.add(0);<br><br><br>        dfs(graph,0,list,visited,ans);<br>        return ans;<br><br><br><br>        <br>        <br>    }<br><br>    public void dfs(int[][]graph,int src,List&lt;Integer&gt;temp,int visited[],List&lt;List&lt;Integer&gt;&gt;ans){<br>        if(temp.size()&gt;graph.length){<br>            return;<br>        }<br><br>        if(src==graph.length-1){<br>            ans.add(new ArrayList&lt;&gt;(temp));<br>            return;<br>        }<br><br><br>        int curr[]=graph[src];<br><br>        for(int i=0;i&lt;curr.length;i++){<br>            if(visited[curr[i]]==0){<br>                visited[curr[i]]=1;<br>                temp.add(curr[i]);<br>                dfs(graph,curr[i],temp,visited,ans);<br>                temp.remove(temp.size()-1);<br>                visited[curr[i]]=0;<br><br><br>            }<br>        }<br><br>        <br><br><br>    }<br>}</pre><p>dFS in matrix:-</p><pre>class Solution {<br>    public int numIslands(char[][] grid) {<br><br>        int visited[][]=new int[grid.length][grid[0].length];<br><br>        int count=0;<br>        for(int i=0;i&lt;visited.length;i++){<br>            for(int j=0;j&lt;visited[0].length;j++){<br>                if(grid[i][j]==&#39;1&#39; &amp;&amp; visited[i][j]==0){<br>                    count++;<br>                    dfs(grid,visited,i,j);<br>                }<br>            }<br>        }<br>        return count;<br>        <br>    }<br><br><br>    public void dfs(char[][]grid,int visited[][],int i ,int j){<br>        if(i&lt;0 || i&gt;visited.length-1 || j&lt;0 || j&gt;visited[0].length-1 || grid[i][j]==&#39;0&#39; || visited[i][j]==1){<br>            return;<br>        }<br>        visited[i][j]=1;<br>        int dir[][]={{1,0},{-1,0},{0,-1},{0,1}};<br>        for(int k=0;k&lt;dir.length;k++){<br>            int x=i+dir[k][0];<br>            int y=j+dir[k][1];<br><br>            dfs(grid,visited,x,y);<br>        }<br>    }<br>}</pre><p>BFS</p><pre>class Solution {<br>    public boolean validPath(int n, int[][] edges, int source, int destination) {<br><br>        ArrayList&lt;ArrayList&lt;Integer&gt;&gt;list=new ArrayList&lt;&gt;();<br><br>        for(int i=0;i&lt;n;i++){<br>            list.add(new ArrayList&lt;&gt;());<br><br>        }<br><br>        for(int i=0;i&lt;edges.length;i++){<br>            list.get(edges[i][0]).add(edges[i][1]);<br>            list.get(edges[i][1]).add(edges[i][0]);<br>        }<br><br>        boolean visited[]=new boolean[n];<br><br>        LinkedList&lt;Integer&gt;queue=new LinkedList&lt;&gt;();<br><br>        queue.addLast(source);<br>        visited[source]=true;<br><br>        while(queue.size()&gt;0){<br>            int size=queue.size();<br><br>            for(int i=0;i&lt;size;i++){<br>                int temp=queue.removeFirst();<br><br>                if(temp==destination){<br>                    return true;<br>                }<br><br>                for(int j=0;j&lt;list.get(temp).size();j++){<br>                    if(!visited[list.get(temp).get(j)]){<br>                        visited[list.get(temp).get(j)]=true;<br>                        queue.addLast(list.get(temp).get(j));<br>                    }<br>                }<br>            }<br>        }<br><br>        return false;<br><br>        <br><br><br>        <br>    }<br>}</pre><p>find center</p><pre>public int findCenter(int[][] edges) {<br><br>        ArrayList&lt;ArrayList&lt;Integer&gt;&gt;list=new ArrayList&lt;&gt;();<br><br>        for(int i=0;i&lt;=edges.length+1;i++){<br>            list.add(new ArrayList&lt;&gt;());<br><br>        }<br><br>        for(int i=0;i&lt;edges.length;i++){<br>            list.get(edges[i][0]).add(edges[i][1]);<br>            list.get(edges[i][1]).add(edges[i][0]);<br>        }<br><br>        for(int i=1;i&lt;list.size();i++){<br><br>            if(list.get(i).size()==edges.length){<br>                return i;<br>            }<br><br><br><br>        }<br><br>        return -1;<br>        <br>    }<br></pre><pre>boolean visited[] = new boolean[list.size()];<br>System.out.println(Arrays.toString(visited));<br><br></pre><pre>Google SWE Interview — Complete Graph DSA Roadmap<br>Google-focused • Java • Beginner to Advanced<br>For Google, I recommend preparing 120–150 unique graph problems, emphasizing medium and hard problems, graph modeling, algorithm selection, and optimization.<br>This roadmap is organized into 18 topics, covering the major graph patterns relevant to Google SWE interviews. Each topic has Concept, Medium, and Hard practice. Some foundational problems are officially rated Medium, and the levels below indicate learning progression rather than exact LeetCode difficulty.<br>The list is curated for Google-style preparation, not a verified list of questions Google currently asks.<br>Phase 1 — Graph Fundamentals<br>1. Graph Representation, DFS and BFS<br>Concept<br>1. 1971. Find if Path Exists in Graph. --&gt; done X2<br>2. 1791. Find Center of Star Graph.  --&gt; done X2<br>3. 997. Find the Town Judge.  --&gt; done x2 <br>4. 841. Keys and Rooms.  --&gt; done x2<br>5. 547. Number of Provinces.  --&gt;done X2<br>Medium<br>1. 133. Clone Graph<br>2. 200. Number of Islands --&gt; done x2<br>3. 695. Max Area of Island --&gt; done x2<br>4. 1466. Reorder Routes to Make All Paths Lead to City Zero --&gt; done x2<br>5. 797. All Paths From Source to Target --&gt; done x2<br>Hard<br>1. 329. Longest Increasing Path in a Matrix --&gt; done<br>2. 827. Making A Large Island. --&gt; done (good)<br>3. 1568. Minimum Number of Days to Disconnect Island --&gt; done (good)<br>4. 1761. Minimum Degree of a Connected Trio in a Graph<br>5. 2092. Find All People With Secret<br>2. BFS, Multi-Source BFS and Grid Traversal<br>Concept<br>1. 733. Flood Fill. --&gt; done x2<br>2. 463. Island Perimeter --&gt; done x2<br>3. 690. Employee Importance --&gt;done x2<br>4. 994. Rotting Oranges --&gt; done x2<br>5. 542. 01 Matrix. --&gt; done x2<br>Medium<br>1. 1091. Shortest Path in Binary Matrix. --&gt; done<br>2. 752. Open the Lock --&gt; done<br>3. 433. Minimum Genetic Mutation. -&gt;done<br>4. 934. Shortest Bridge. --&gt; done<br>5. 1926. Nearest Exit from Entrance in Maze. --&gt; done<br>Hard<br>1. 127. Word Ladder<br>2. 126. Word Ladder II<br>3. 815. Bus Routes<br>4. 1293. Shortest Path in a Grid with Obstacles Elimination<br>5. 864. Shortest Path to Get All Keys<br>3. DFS on Grids, Boundaries and Components<br>Concept<br>1. 1020. Number of Enclaves --&gt; done<br>2. 1254. Number of Closed Islands. -&gt; done<br>3. 1905. Count Sub Islands. --&gt; done<br>4. 1034. Coloring A Border. --&gt; done<br>5. 733. Flood Fill --&gt; done<br>Medium<br>1. 130. Surrounded Regions --&gt; done<br>2. 417. Pacific Atlantic Water Flow<br>3. 399. Evaluate Division<br>4. 886. Possible Bipartition --&gt; done<br>5. 1559. Detect Cycles in 2D Grid<br>Hard<br>1. 778. Swim in Rising Water --&gt; done<br>2. 407. Trapping Rain Water II<br>3. 2328. Number of Increasing Paths in a Grid<br>4. 1219. Path with Maximum Gold<br>5. 980. Unique Paths III<br>Phase 2 — Graph Structure and Dependencies<br>4. Cycle Detection and Bipartite Graphs<br>Concept<br>1. 684. Redundant Connection --&gt; done<br>2. 785. Is Graph Bipartite? --&gt; done<br>3. 207. Course Schedule --&gt; done<br>4. 802. Find Eventual Safe States --&gt; done<br>5. 886. Possible Bipartition --&gt; done<br>Medium<br>1. 210. Course Schedule II --&gt; done<br>2. 2360. Longest Cycle in a Graph<br>3. 2608. Shortest Cycle in a Graph<br>4. 2127. Maximum Employees to Be Invited to a Meeting<br>5. 2876. Count Visited Nodes in a Directed Graph<br>Hard<br>1. 685. Redundant Connection II<br>2. 1591. Strange Printer II<br>3. 1857. Largest Color Value in a Directed Graph<br>4. 1203. Sort Items by Groups Respecting Dependencies<br>5. 2076. Process Restricted Friend Requests<br>5. Topological Sorting — Kahn&#39;s Algorithm and DFS<br>Concept<br>1. 207. Course Schedule --&gt; done<br>2. 210. Course Schedule II --&gt; done<br>3. 2115. Find All Possible Recipes from Given Supplies --&gt; done<br>4. 1462. Course Schedule IV --&gt; done<br>5. 802. Find Eventual Safe States. -&gt; done<br>Medium<br>1. 310. Minimum Height Trees --&gt; done<br>2. 2192. All Ancestors of a Node in a Directed Acyclic Graph. --&gt; done<br>3. 2392. Build a Matrix With Conditions<br>4. 1136. Parallel Courses --&gt; done<br>5. 2050. Parallel Courses III --&gt; done<br>Hard<br>1. 269. Alien Dictionary--&gt; done<br>2. 1203. Sort Items by Groups Respecting Dependencies --&gt; good done<br>3. 1857. Largest Color Value in a Directed Graph--&gt; good done<br>4. 1591. Strange Printer II<br>5. 1494. Parallel Courses II<br>6. Disjoint Set Union — Union Find<br>Concept<br>1. 547. Number of Provinces--&gt; done<br>2. 684. Redundant Connection --&gt; done<br>3. 1319. Number of Operations to Make Network Connected --&gt; done<br>4. 990. Satisfiability of Equality Equations<br>5. 1971. Find if Path Exists in Graph --&gt; done<br>Medium<br>1. 721. Accounts Merge<br>2. 947. Most Stones Removed with Same Row or Column<br>3. 1202. Smallest String With Swaps<br>4. 1061. Lexicographically Smallest Equivalent String<br>5. 959. Regions Cut By Slashes<br>Hard<br>1. 685. Redundant Connection II<br>2. 827. Making A Large Island<br>3. 1579. Remove Max Number of Edges to Keep Graph Fully Traversable<br>4. 1697. Checking Existence of Edge Length Limited Paths<br>5. 2092. Find All People With Secret<br>Phase 3 — Weighted Graph Algorithms<br>7. Dijkstra&#39;s Algorithm<br>Concept<br>1. 743. Network Delay Time<br>2. 1514. Path with Maximum Probability<br>3. 1631. Path With Minimum Effort<br>4. 1976. Number of Ways to Arrive at Destination<br>5. 3341. Find Minimum Time to Reach Last Room I<br>Medium<br>1. 787. Cheapest Flights Within K Stops<br>2. 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance<br>3. 778. Swim in Rising Water<br>4. 1928. Minimum Cost to Reach Destination in Time<br>5. 2577. Minimum Time to Visit a Cell In a Grid<br>Hard<br>1. 2203. Minimum Weighted Subgraph With the Required Paths<br>2. 2699. Modify Graph Edge Weights<br>3. 1786. Number of Restricted Paths From First to Last Node<br>4. 2045. Second Minimum Time to Reach Destination<br>5. 3123. Find Edges in Shortest Paths<br>8. Bellman-Ford, Floyd-Warshall and 0-1 BFS<br>Concept<br>1. 787. Cheapest Flights Within K Stops<br>2. 743. Network Delay Time<br>3. 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance<br>4. 1462. Course Schedule IV<br>5. 2976. Minimum Cost to Convert String I<br>Medium<br>1. 1368. Minimum Cost to Make at Least One Valid Path in a Grid<br>2. 2290. Minimum Obstacle Removal to Reach Corner<br>3. 2642. Design Graph With Shortest Path Calculator<br>4. 2959. Number of Possible Sets of Closing Branches<br>5. 2977. Minimum Cost to Convert String II<br>Hard<br>1. 2203. Minimum Weighted Subgraph With the Required Paths<br>2. 2699. Modify Graph Edge Weights<br>3. 2577. Minimum Time to Visit a Cell In a Grid<br>4. 1928. Minimum Cost to Reach Destination in Time<br>5. 2045. Second Minimum Time to Reach Destination<br>9. Minimum Spanning Tree — Prim and Kruskal<br>Concept<br>1. 1584. Min Cost to Connect All Points<br>2. 1135. Connecting Cities With Minimum Cost<br>3. 1168. Optimize Water Distribution in a Village<br>4. 2492. Minimum Score of a Path Between Two Cities<br>5. 1631. Path With Minimum Effort<br>Medium<br>1. 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree<br>2. 778. Swim in Rising Water<br>3. 1579. Remove Max Number of Edges to Keep Graph Fully Traversable<br>4. 1697. Checking Existence of Edge Length Limited Paths<br>5. 1724. Checking Existence of Edge Length Limited Paths II<br>Hard<br>1. 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree<br>2. 1579. Remove Max Number of Edges to Keep Graph Fully Traversable<br>3. 1697. Checking Existence of Edge Length Limited Paths<br>4. 1724. Checking Existence of Edge Length Limited Paths II<br>5. 2092. Find All People With Secret<br>Phase 4 — Advanced Graph Structure<br>10. Bridges and Articulation Points<br>Concept<br>1. 1192. Critical Connections in a Network<br>2. 1568. Minimum Number of Days to Disconnect Island<br>3. 684. Redundant Connection<br>4. 1319. Number of Operations to Make Network Connected<br>5. 2608. Shortest Cycle in a Graph<br>Medium<br>1. 1192. Critical Connections in a Network<br>2. 1568. Minimum Number of Days to Disconnect Island<br>3. 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree<br>4. 928. Minimize Malware Spread II<br>5. 924. Minimize Malware Spread<br>Hard<br>1. 1192. Critical Connections in a Network<br>2. 1568. Minimum Number of Days to Disconnect Island<br>3. 928. Minimize Malware Spread II<br>4. 2608. Shortest Cycle in a Graph<br>5. 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree<br>This is a specialized topic with fewer direct LeetCode examples. Repeated problems are for applying different techniques, not additional unique practice.<br>11. Strongly Connected Components — Kosaraju and Tarjan<br>Concept<br>1. 207. Course Schedule<br>2. 802. Find Eventual Safe States<br>3. 2360. Longest Cycle in a Graph<br>4. 2127. Maximum Employees to Be Invited to a Meeting<br>5. 2876. Count Visited Nodes in a Directed Graph<br>Medium<br>1. 1462. Course Schedule IV<br>2. 802. Find Eventual Safe States<br>3. 2360. Longest Cycle in a Graph<br>4. 1857. Largest Color Value in a Directed Graph<br>5. 1591. Strange Printer II<br>Hard<br>1. 1857. Largest Color Value in a Directed Graph<br>2. 1591. Strange Printer II<br>3. 1203. Sort Items by Groups Respecting Dependencies<br>4. 2360. Longest Cycle in a Graph<br>5. 2127. Maximum Employees to Be Invited to a Meeting<br>Several questions here teach related directed-cycle concepts rather than requiring SCC algorithms. Practice implementing Kosaraju and Tarjan independently as well.<br>12. Eulerian Path, Circuit and Hierholzer&#39;s Algorithm<br>Concept<br>1. 332. Reconstruct Itinerary<br>2. 2097. Valid Arrangement of Pairs<br>3. 753. Cracking the Safe<br>4. 1971. Find if Path Exists in Graph<br>5. 684. Redundant Connection<br>Medium<br>1. 332. Reconstruct Itinerary<br>2. 2097. Valid Arrangement of Pairs<br>3. 753. Cracking the Safe<br>4. 797. All Paths From Source to Target<br>5. 980. Unique Paths III<br>Hard<br>1. 753. Cracking the Safe<br>2. 2097. Valid Arrangement of Pairs<br>3. 332. Reconstruct Itinerary<br>4. 847. Shortest Path Visiting All Nodes<br>5. 943. Find the Shortest Superstring<br>The first three are the direct Eulerian practice set. The remaining questions are related path problems, not Eulerian-path problems.<br>Phase 5 — Graph + DP (Very Important for Google)<br>13. DAG DP and Longest Path<br>Concept<br>1. 797. All Paths From Source to Target<br>2. 329. Longest Increasing Path in a Matrix<br>3. 2328. Number of Increasing Paths in a Grid<br>4. 2050. Parallel Courses III<br>5. 1462. Course Schedule IV<br>Medium<br>1. 1857. Largest Color Value in a Directed Graph<br>2. 2192. All Ancestors of a Node in a Directed Acyclic Graph<br>3. 1786. Number of Restricted Paths From First to Last Node<br>4. 1976. Number of Ways to Arrive at Destination<br>5. 2328. Number of Increasing Paths in a Grid<br>Hard<br>1. 1857. Largest Color Value in a Directed Graph<br>2. 2050. Parallel Courses III<br>3. 2328. Number of Increasing Paths in a Grid<br>4. 1786. Number of Restricted Paths From First to Last Node<br>5. 1494. Parallel Courses II<br>14. Bitmask BFS and State-Space DP<br>Concept<br>1. 752. Open the Lock<br>2. 433. Minimum Genetic Mutation<br>3. 847. Shortest Path Visiting All Nodes<br>4. 980. Unique Paths III<br>5. 864. Shortest Path to Get All Keys<br>Medium<br>1. 847. Shortest Path Visiting All Nodes<br>2. 864. Shortest Path to Get All Keys<br>3. 943. Find the Shortest Superstring<br>4. 1494. Parallel Courses II<br>5. 1125. Smallest Sufficient Team<br>Hard<br>1. 847. Shortest Path Visiting All Nodes<br>2. 864. Shortest Path to Get All Keys<br>3. 943. Find the Shortest Superstring<br>4. 1494. Parallel Courses II<br>5. 1349. Maximum Students Taking Exam<br>15. Tree Algorithms as Graphs — LCA, Diameter and Rerooting<br>Concept<br>1. 104. Maximum Depth of Binary Tree<br>2. 543. Diameter of Binary Tree<br>3. 112. Path Sum<br>4. 226. Invert Binary Tree<br>5. 235. Lowest Common Ancestor of a Binary Search Tree<br>Medium<br>1. 236. Lowest Common Ancestor of a Binary Tree<br>2. 310. Minimum Height Trees<br>3. 1245. Tree Diameter<br>4. 863. All Nodes Distance K in Binary Tree<br>5. 1519. Number of Nodes in the Sub-Tree With the Same Label<br>Hard<br>1. 834. Sum of Distances in Tree<br>2. 124. Binary Tree Maximum Path Sum<br>3. 2246. Longest Path With Different Adjacent Characters<br>4. 2458. Height of Binary Tree After Subtree Removal Queries<br>5. 1483. Kth Ancestor of a Tree Node<br>Phase 6 — Expert-Level Graph Patterns<br>16. Functional Graphs and Advanced Cycle Problems<br>Concept<br>1. 2360. Longest Cycle in a Graph<br>2. 2127. Maximum Employees to Be Invited to a Meeting<br>3. 2876. Count Visited Nodes in a Directed Graph<br>4. 802. Find Eventual Safe States<br>5. 207. Course Schedule<br>Medium<br>1. 2360. Longest Cycle in a Graph<br>2. 2127. Maximum Employees to Be Invited to a Meeting<br>3. 2876. Count Visited Nodes in a Directed Graph<br>4. 2359. Find Closest Node to Given Two Nodes<br>5. 2608. Shortest Cycle in a Graph<br>Hard<br>1. 2127. Maximum Employees to Be Invited to a Meeting<br>2. 2876. Count Visited Nodes in a Directed Graph<br>3. 2360. Longest Cycle in a Graph<br>4. 1857. Largest Color Value in a Directed Graph<br>5. 2608. Shortest Cycle in a Graph<br>17. Max Flow, Min Cut and Graph Matching<br>Concept<br>1. 785. Is Graph Bipartite?<br>2. 886. Possible Bipartition<br>3. 1820. Maximum Number of Accepted Invitations<br>4. 1349. Maximum Students Taking Exam<br>5. 2123. Minimum Operations to Remove Adjacent Ones in Matrix<br>Medium<br>1. 1820. Maximum Number of Accepted Invitations<br>2. 1349. Maximum Students Taking Exam<br>3. 2123. Minimum Operations to Remove Adjacent Ones in Matrix<br>4. 1947. Maximum Compatibility Score Sum<br>5. 1066. Campus Bikes II<br>Hard<br>1. 1349. Maximum Students Taking Exam<br>2. 2123. Minimum Operations to Remove Adjacent Ones in Matrix<br>3. 1820. Maximum Number of Accepted Invitations<br>4. 1947. Maximum Compatibility Score Sum<br>5. 1066. Campus Bikes II<br>This is a small LeetCode matching set with repeats. For true max-flow coverage, also implement Ford-Fulkerson, Edmonds-Karp and Dinic using standalone exercises.<br>18. Mixed Google-Style Graph Challenges<br>Concept<br>1. 399. Evaluate Division<br>2. 332. Reconstruct Itinerary<br>3. 399. Evaluate Division<br>4. 721. Accounts Merge<br>5. 417. Pacific Atlantic Water Flow<br>Medium<br>1. 127. Word Ladder<br>2. 787. Cheapest Flights Within K Stops<br>3. 1631. Path With Minimum Effort<br>4. 2092. Find All People With Secret<br>5. 332. Reconstruct Itinerary<br>Hard<br>1. 847. Shortest Path Visiting All Nodes<br>2. 126. Word Ladder II<br>3. 1192. Critical Connections in a Network<br>4. 2699. Modify Graph Edge Weights<br>5. 2203. Minimum Weighted Subgraph With the Required Paths<br><br>Your Google preparation schedule<br>Phase Topics Suggested time<br>1 Fundamentals, BFS, DFS, grids 2 weeks<br>2 Cycles, topological sort, DSU 2 weeks<br>3 Shortest paths, MST 2 weeks<br>4 Bridges, SCC, Eulerian paths 2 weeks<br>5 Graph DP, bitmask, tree algorithms 2 weeks<br>6 Advanced patterns and mixed mocks 2 weeks</pre><p>Bipertitie:-</p><pre>class Solution {<br>    public boolean possibleBipartition(int n, int[][] edges) {<br><br><br>        ArrayList&lt;ArrayList&lt;Integer&gt;&gt;list=new ArrayList&lt;&gt;();<br><br>        for(int i=0;i&lt;n;i++){<br>            list.add(new ArrayList&lt;&gt;());<br><br>        }<br><br>        for(int i=0;i&lt;edges.length;i++){<br>            list.get(edges[i][0]-1).add(edges[i][1]-1);<br>            list.get(edges[i][1]-1).add(edges[i][0]-1);<br>        }<br><br>        int visited[]=new int[n];<br><br><br>        LinkedList&lt;Integer&gt;queue=new LinkedList&lt;&gt;();<br><br>        int count=0;<br><br><br>        for(int i=0;i&lt;n;i++){<br><br><br>            if(visited[i]==0){<br><br><br>                queue.addLast(i);<br>            visited[i]=count;<br><br>            while(queue.size()&gt;0){<br>                int size=queue.size();<br>                count++;<br><br>                for(int j=0;j&lt;size;j++){<br>                    int temp=queue.removeFirst();<br><br>                    <br><br>                    for(int k=0;k&lt;list.get(temp).size();k++){<br>                        if(visited[list.get(temp).get(k)]==0){<br>                            visited[list.get(temp).get(k)]=count;<br>                            queue.addLast(list.get(temp).get(k));<br>                        }else if(count%2!=visited[list.get(temp).get(k)]%2){<br>                            return false;<br>                        }<br>                    }<br>                }<br>            }<br><br>     <br><br><br>            }<br><br>        }<br><br><br>        return true;<br><br>        <br><br><br>        <br>    }<br>}</pre><p>To find a cycle in undirected graph :-</p><pre>Use DFS with parent tracking to detect a cycle in each connected region of the grid.<br>From a cell, explore neighboring cells that have the same character. For each such neighbor:<br>- If it hasn’t been visited, visit it and pass the current cell as its parent.<br>- If it has already been visited and it isn’t the parent, you found a cycle.</pre><pre>boolean hasCycle(List&lt;List&lt;Integer&gt;&gt; graph, int n) {<br>    boolean[] visited = new boolean[n];<br><br>    for (int node = 0; node &lt; n; node++) {<br>        if (!visited[node] &amp;&amp; dfs(graph, node, -1, visited)) {<br>            return true;<br>        }<br>    }<br>    return false;<br>}<br><br>boolean dfs(List&lt;List&lt;Integer&gt;&gt; graph, int node, int parent, boolean[] visited) {<br>    visited[node] = true;<br><br>    for (int neighbor : graph.get(node)) {<br>        if (!visited[neighbor]) {<br>            if (dfs(graph, neighbor, node, visited)) {<br>                return true;<br>            }<br>        } else if (neighbor != parent) {<br>            return true;<br>        }<br>    }<br>    return false;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1103b89e9e48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merge Interval]]></title>
            <link>https://medium.com/@gandharvdalal24/merge-interval-3d2f0238421e?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d2f0238421e</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 19:48:55 GMT</pubDate>
            <atom:updated>2026-11-01T19:48:55.782Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Merge, insert, and normalize intervals</h3><p>Practice sorting, overlap conditions, touching endpoints, and handling already sorted inputs.</p><ul><li><a href="https://leetcode.com/problems/merge-intervals/">56. Merge Intervals</a> — merge overlapping intervals.</li><li><a href="https://leetcode.com/problems/insert-interval/">57. Insert Interval</a> — insert into a sorted, non-overlapping list.</li><li><a href="https://leetcode.com/problems/interval-list-intersections/">986. Interval List Intersections</a> — intersect two sorted interval lists.</li><li><a href="https://leetcode.com/problems/summary-ranges/">228. Summary Ranges</a> — compress consecutive values into ranges.</li><li><a href="https://leetcode.com/problems/data-stream-as-disjoint-intervals/">352. Data Stream as Disjoint Intervals</a> — maintain merged ranges as values arrive.</li><li><a href="https://leetcode.com/problems/missing-ranges/">163. Missing Ranges</a> — find uncovered gaps in a bounded range.</li></ul><h3>2. Detect overlaps and remove intervals</h3><p>These test whether intervals conflict and how to eliminate the fewest conflicts.</p><ul><li><a href="https://leetcode.com/problems/meeting-rooms/">252. Meeting Rooms</a> — determine whether any intervals overlap.</li><li><a href="https://leetcode.com/problems/non-overlapping-intervals/">435. Non-overlapping Intervals</a> — remove the minimum number to eliminate overlaps.</li><li><a href="https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/">452. Minimum Number of Arrows to Burst Balloons</a> — choose the minimum points that hit every interval.</li><li><a href="https://leetcode.com/problems/maximum-length-of-pair-chain/">646. Maximum Length of Pair Chain</a> — choose the largest compatible subset.</li><li><a href="https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/">2406. Divide Intervals Into Minimum Number of Groups</a> — assign overlapping intervals to separate groups.</li></ul><h3>3. Scheduling and resource allocation</h3><p>These model meetings, jobs, or courses competing for time or resources.</p><ul><li><a href="https://leetcode.com/problems/meeting-rooms-ii/">253. Meeting Rooms II</a> — minimum rooms for all meetings.</li><li><a href="https://leetcode.com/problems/meeting-rooms-iii/">2402. Meeting Rooms III</a> — assign meetings to rooms under scheduling rules.</li><li><a href="https://leetcode.com/problems/course-schedule-iii/">630. Course Schedule III</a> — maximize courses completed before deadlines.</li><li><a href="https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/">1353. Maximum Number of Events That Can Be Attended</a> — attend the maximum number of events.</li><li><a href="https://leetcode.com/problems/maximum-profit-in-job-scheduling/">1235. Maximum Profit in Job Scheduling</a> — weighted interval scheduling with DP.</li><li><a href="https://leetcode.com/problems/employee-free-time/">759. Employee Free Time</a> — find gaps shared across schedules.</li></ul><h3>4. Cover a target range</h3><p>These ask for the fewest intervals or actions needed to cover a continuous target.</p><ul><li><a href="https://leetcode.com/problems/video-stitching/">1024. Video Stitching</a> — cover a target timeline with the fewest clips.</li><li><a href="https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/">1326. Minimum Number of Taps to Open to Water a Garden</a> — cover a line segment with tap ranges.</li><li><a href="https://leetcode.com/problems/jump-game-ii/">45. Jump Game II</a> — related greedy range-expansion pattern.</li><li><a href="https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/">1893. Check if All the Integers in a Range Are Covered</a> — test whether intervals cover a target range.</li></ul><h3>5. Sweep line and event ordering</h3><p>Turn interval starts and ends into events, sort them, and track what is active. Pay close attention to inclusive versus exclusive endpoints.</p><ul><li><a href="https://leetcode.com/problems/car-pooling/">1094. Car Pooling</a> — track passenger counts over route positions.</li><li><a href="https://leetcode.com/problems/brightest-position-on-street/">2021. Brightest Position on Street</a> — find the point covered by the most ranges.</li><li><a href="https://leetcode.com/problems/number-of-flowers-in-full-bloom/">2251. Number of Flowers in Full Bloom</a> — count active intervals at query times.</li><li><a href="https://leetcode.com/problems/minimum-interval-to-include-each-query/">1851. Minimum Interval to Include Each Query</a> — find the smallest covering interval for each query.</li><li><a href="https://leetcode.com/problems/the-skyline-problem/">218. The Skyline Problem</a> — maintain the maximum active height.</li><li><a href="https://leetcode.com/problems/rectangle-area-ii/">850. Rectangle Area II</a> — union area using a sweep line and coordinate compression.</li><li><a href="https://leetcode.com/problems/perfect-rectangle/">391. Perfect Rectangle</a> — rectangle coverage and overlap conditions.</li></ul><h3>6. Heaps and active intervals</h3><p>Use a priority queue when the next interval to process depends on the smallest end, shortest range, or best active choice.</p><ul><li><a href="https://leetcode.com/problems/meeting-rooms-ii/">253. Meeting Rooms II</a> — min-heap of room end times.</li><li><a href="https://leetcode.com/problems/meeting-rooms-iii/">2402. Meeting Rooms III</a> — heaps for available rooms and busy rooms.</li><li><a href="https://leetcode.com/problems/course-schedule-iii/">630. Course Schedule III</a> — max-heap to discard the longest course when needed.</li><li><a href="https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/">1353. Maximum Number of Events That Can Be Attended</a> — min-heap of events ending soonest.</li><li><a href="https://leetcode.com/problems/minimum-interval-to-include-each-query/">1851. Minimum Interval to Include Each Query</a> — min-heap of eligible intervals by length.</li><li><a href="https://leetcode.com/problems/the-skyline-problem/">218. The Skyline Problem</a> — heap of active building heights.</li></ul><h3>7. Calendar and dynamic interval updates</h3><p>These require adding intervals over time while checking overlap counts or maintaining covered ranges.</p><ul><li><a href="https://leetcode.com/problems/my-calendar-i/">729. My Calendar I</a> — reject bookings that overlap.</li><li><a href="https://leetcode.com/problems/my-calendar-ii/">731. My Calendar II</a> — allow double booking, reject triple booking.</li><li><a href="https://leetcode.com/problems/my-calendar-iii/">732. My Calendar III</a> — report the maximum overlap after each booking.</li><li><a href="https://leetcode.com/problems/range-module/">715. Range Module</a> — add, remove, and query covered ranges.</li><li><a href="https://leetcode.com/problems/falling-squares/">699. Falling Squares</a> — update heights over overlapping coordinate ranges.</li><li><a href="https://leetcode.com/problems/data-stream-as-disjoint-intervals/">352. Data Stream as Disjoint Intervals</a> — dynamically merge inserted points.</li></ul><h3>8. Interval dynamic programming</h3><p>These use intervals as DP states, often by choosing a split point or scheduling compatible jobs.</p><ul><li><a href="https://leetcode.com/problems/maximum-profit-in-job-scheduling/">1235. Maximum Profit in Job Scheduling</a> — weighted scheduling with binary search and DP.</li><li><a href="https://leetcode.com/problems/burst-balloons/">312. Burst Balloons</a> — choose the last balloon in a subinterval.</li><li><a href="https://leetcode.com/problems/minimum-cost-to-cut-a-stick/">1547. Minimum Cost to Cut a Stick</a> — choose the first cut in a subinterval.</li><li><a href="https://leetcode.com/problems/minimum-cost-to-merge-stones/">1000. Minimum Cost to Merge Stones</a> — interval DP with constrained merging.</li><li><a href="https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/">1335. Minimum Difficulty of a Job Schedule</a> — partition an ordered sequence into day ranges.</li><li><a href="https://leetcode.com/problems/minimum-score-triangulation-of-polygon/">1039. Minimum Score Triangulation of Polygon</a> — split a range around a triangle vertex.</li></ul><h3>9. Range-query data structures</h3><p>These are adjacent to interval problems: the focus is efficiently querying or updating ranges.</p><ul><li><a href="https://leetcode.com/problems/range-sum-query-mutable/">307. Range Sum Query — Mutable</a> — point updates and range sums.</li><li><a href="https://leetcode.com/problems/range-sum-query-2d-mutable/">308. Range Sum Query 2D — Mutable</a> — 2D range updates and queries.</li><li><a href="https://leetcode.com/problems/falling-squares/">699. Falling Squares</a> — coordinate-compressed range maximum updates.</li><li><a href="https://leetcode.com/problems/range-module/">715. Range Module</a> — range add/remove/query.</li><li><a href="https://leetcode.com/problems/my-calendar-ii/">731. My Calendar II</a> — overlap counting under bookings.</li><li><a href="https://leetcode.com/problems/my-calendar-iii/">732. My Calendar III</a> — maximum overlap queries.</li></ul><h3>10. Geometry and rectangle intervals</h3><p>These extend one-dimensional interval reasoning into two dimensions.</p><ul><li><a href="https://leetcode.com/problems/rectangle-area/">223. Rectangle Area</a> — area of two rectangles and their overlap.</li><li><a href="https://leetcode.com/problems/perfect-rectangle/">391. Perfect Rectangle</a> — determine whether smaller rectangles exactly tile a larger one.</li><li><a href="https://leetcode.com/problems/rectangle-area-ii/">850. Rectangle Area II</a> — union area of many rectangles.</li><li><a href="https://leetcode.com/problems/the-skyline-problem/">218. The Skyline Problem</a> — buildings represented as horizontal intervals with heights.</li><li><a href="https://leetcode.com/problems/falling-squares/">699. Falling Squares</a> — overlapping horizontal spans with changing heights.</li></ul><h3>11. A few advanced interval-adjacent problems</h3><p>These broaden the toolkit beyond the standard “sort and merge” pattern.</p><ul><li><a href="https://leetcode.com/problems/range-module/">715. Range Module</a> — ordered range updates and queries.</li><li><a href="https://leetcode.com/problems/data-stream-as-disjoint-intervals/">352. Data Stream as Disjoint Intervals</a> — ordered set or binary search over ranges.</li><li><a href="https://leetcode.com/problems/minimum-interval-to-include-each-query/">1851. Minimum Interval to Include Each Query</a> — offline queries plus a heap.</li><li><a href="https://leetcode.com/problems/number-of-flowers-in-full-bloom/">2251. Number of Flowers in Full Bloom</a> — offline sorting or binary search over endpoints.</li><li><a href="https://leetcode.com/problems/the-skyline-problem/">218. The Skyline Problem</a> — sweep line plus a multiset or heap.</li></ul><h3>Suggested practice order</h3><ol><li><strong>Start:</strong> 56, 57, 252, 435, 986</li><li><strong>Greedy:</strong> 452, 646, 1024, 1326</li><li><strong>Scheduling and heaps:</strong> 253, 630, 1353, 1235, 2402</li><li><strong>Sweep line:</strong> 1094, 2021, 2251, 1851, 218</li><li><strong>Dynamic updates:</strong> 729, 731, 732, 715, 352</li><li><strong>DP and geometry:</strong> 312, 1547, 1000, 850, 699</li></ol><p>That gives you practice across the major interval variations. A few are <strong>interval-adjacent</strong> rather than classic merge-interval problems, but they’re useful once the core patterns feel comfortable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d2f0238421e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JAVA]]></title>
            <link>https://medium.com/@gandharvdalal24/java-d28c739c2f85?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/d28c739c2f85</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 09:28:11 GMT</pubDate>
            <atom:updated>2026-11-28T08:59:17.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Interview Notes: Core Java and Multithreading</h3><p>Use these notes to understand each topic and to build concise interview answers. The examples use standard Java syntax.</p><h3>1. == vs. equals()</h3><p>== compares <strong>primitive values</strong> or, for objects, whether two references point to the <strong>same object</strong>.</p><p>equals() compares objects according to their equality definition. Unless a class overrides it, Object.equals() behaves like ==.</p><pre>String a = new String(&quot;Cisco&quot;);<br>String b = new String(&quot;Cisco&quot;);</pre><pre>System.out.println(a == b);      // false: different objects<br>System.out.println(a.equals(b)); // true: same text</pre><p>For primitives:</p><pre>int x = 5;<br>int y = 5;<br>System.out.println(x == y); // true: same primitive value</pre><p><strong>Interview answer:</strong> “For objects, == checks reference identity. equals() checks logical equality, if the class defines that behavior.”</p><h3>2. The equals() and hashCode() contract</h3><p>When overriding equals(), you should also override hashCode().</p><p>The key rule is:</p><blockquote><em>If </em><em>a.equals(b) is </em><em>true, then </em><em>a.hashCode() must equal </em><em>b.hashCode().</em></blockquote><p>The reverse is not required: two unequal objects can have the same hash code.</p><pre>import java.util.Objects;</pre><pre>class Employee {<br>    private final int id;</pre><pre>    Employee(int id) {<br>        this.id = id;<br>    }</pre><pre>    @Override<br>    public boolean equals(Object obj) {<br>        if (this == obj) return true;<br>        if (!(obj instanceof Employee other)) return false;<br>        return id == other.id;<br>    }</pre><pre>    @Override<br>    public int hashCode() {<br>        return Objects.hash(id);<br>    }<br>}</pre><p>HashMap and HashSet use the hash code to locate a bucket, then use equals() to check for a matching key or element. If you override equals() but not hashCode(), equal objects may end up in different buckets, causing unexpected lookup or duplicate behavior.</p><p><strong>Good practice:</strong> Don’t change fields used by equals() or hashCode() while an object is being used as a map key.</p><h3>3. Immutable classes</h3><p>An immutable object cannot have its state changed after it is created. String is a familiar example.</p><h3>How to create one</h3><ul><li>Make the class final, so subclasses cannot add mutability.</li><li>Make fields private and final.</li><li>Set all fields in the constructor.</li><li>Don’t provide setters.</li><li>For mutable inputs or fields, make defensive copies.</li></ul><pre>import java.util.Date;</pre><pre>final class EmployeeRecord {<br>    private final String name;<br>    private final Date joiningDate;</pre><pre>    EmployeeRecord(String name, Date joiningDate) {<br>        this.name = name;<br>        this.joiningDate = new Date(joiningDate.getTime()); // Copy input<br>    }</pre><pre>    public String getName() {<br>        return name;<br>    }</pre><pre>    public Date getJoiningDate() {<br>        return new Date(joiningDate.getTime()); // Return a copy<br>    }<br>}</pre><p>Without the copies, a caller could mutate the Date passed in or returned by the getter.</p><p><strong>Benefits:</strong> Immutable objects are easier to reason about, safer to share between threads, and useful as map keys.</p><p>In Java, a String is <strong>immutable</strong>: once created, its characters cannot be changed. An operation that looks like it modifies a string creates a <strong>new</strong> String instead.</p><pre>String text = &quot;hello&quot;;<br>text = text + &quot; world&quot;;</pre><p>The original &quot;hello&quot; stays unchanged. The variable text now refers to a new string, &quot;hello world&quot;.</p><p>Java keeps strings immutable for a few useful reasons:</p><ul><li><strong>Safe sharing:</strong> Many variables and parts of a program can refer to the same string without one of them changing it unexpectedly.</li><li><strong>Reliable hash-based collections:</strong> A string used as a HashMap key keeps the same value and hash code, so the map can still find it.</li><li><strong>String pool:</strong> Java can reuse string literals such as &quot;hello&quot; safely because nobody can change the shared object.</li><li><strong>Security:</strong> Strings often hold values used for file names, class names, URLs, or other sensitive operations. Immutability prevents a value from changing unexpectedly after it has been checked.</li><li><strong>Thread safety:</strong> Multiple threads can read the same string without needing synchronization to protect its contents.</li></ul><p>If you need to build or change text repeatedly, use StringBuilder:</p><pre>StringBuilder text = new StringBuilder(&quot;hello&quot;);<br>text.append(&quot; world&quot;); // modifies the builder</pre><p>Use String for text values and StringBuilder for repeatedly constructing text.</p><h3>4. Composition vs. inheritance</h3><p><strong>Inheritance</strong> models an “is-a” relationship. A Dog <strong>is an</strong> Animal.</p><p><strong>Composition</strong> models a “has-a” relationship. A Car <strong>has an</strong> Engine.</p><pre>class Engine {<br>    void start() {<br>        System.out.println(&quot;Engine started&quot;);<br>    }<br>}</pre><pre>class Car { // Car has an Engine<br>    private final Engine engine = new Engine();</pre><pre>    void start() {<br>        engine.start();<br>    }<br>}</pre><p>Use inheritance when the child truly can be used wherever the parent is expected and its behavior fits the parent’s contract. Use composition when one object uses another object to perform work, or when you want to swap that behavior.</p><p>Composition often reduces tight coupling: a Car can be changed to use a different Engine implementation without becoming a subtype of Engine.</p><h3>Composition vs. inheritance</h3><p>Both are ways to reuse behavior in object-oriented programming.</p><h3>Inheritance: “is-a”</h3><p>A class inherits from another class and gets its behavior.</p><pre>class Animal {<br>    void eat() {<br>        System.out.println(&quot;Eating&quot;);<br>    }<br>}</pre><pre>class Dog extends Animal {<br>    void bark() {<br>        System.out.println(&quot;Barking&quot;);<br>    }<br>}</pre><p>A Dog <strong>is an</strong> Animal, so inheritance can make sense here. Dog gets eat() from Animal.</p><h3>Composition: “has-a”</h3><p>A class holds another object and delegates work to it.</p><pre>class Engine {<br>    void start() {<br>        System.out.println(&quot;Engine started&quot;);<br>    }<br>}</pre><pre>class Car {<br>    private final Engine engine = new Engine();</pre><pre>    void start() {<br>        engine.start();<br>    }<br>}</pre><p>A Car <strong>has an</strong> Engine. It uses the engine’s behavior without becoming an Engine.</p><h3>When to use each</h3><p>Use <strong>inheritance</strong> when there is a genuine “is-a” relationship and the subclass can safely be used wherever the parent is expected.</p><p>Use <strong>composition</strong> when one object needs another object’s behavior. It usually keeps classes more flexible: you can replace or configure the contained object without changing the class hierarchy.</p><p>For example, a Car might use different Engine implementations. With composition, it can receive an Engine through its constructor:</p><pre>class Car {<br>    private final Engine engine;</pre><pre>    Car(Engine engine) {<br>        this.engine = engine;<br>    }</pre><pre>    void start() {<br>        engine.start();<br>    }<br>}</pre><p><strong>Rule of thumb:</strong> model “is-a” with inheritance; model “has-a” with composition. Composition is often the better default for sharing behavior because it creates fewer dependencies between classes.</p><h3>5. How HashMap works and handles collisions</h3><p>A HashMap stores key-value pairs in an internal array of <strong>buckets</strong>.</p><p>At a high level, for put(key, value) it:</p><ol><li>Calls key.hashCode().</li><li>Uses the hash to choose a bucket.</li><li>If the bucket is empty, stores the entry there.</li><li>If another entry is already there, compares keys using equals().</li><li>Replaces the value if an equal key exists; otherwise, stores another entry in that bucket.</li></ol><p>A <strong>collision</strong> occurs when different keys map to the same bucket. HashMap handles collisions by storing multiple entries in that bucket. In modern Java, a heavily populated bucket can be changed from a linked structure into a balanced tree, subject to implementation thresholds.</p><p>Average lookup and insertion are generally <strong>O(1)</strong>; collisions can make operations slower.</p><p><strong>Important:</strong> Keys should have stable hashCode() and equals() behavior while stored in the map.</p><h3>6. HashMap vs. ConcurrentHashMap</h3><h3>HashMap vs. ConcurrentHashMap</h3><p>Both store <strong>key–value pairs</strong> and use hashCode() and equals() to find keys. The main difference is how they behave when multiple threads access them.</p><p>FeatureHashMapConcurrentHashMapThread safetyNot thread-safe for concurrent updatesDesigned for concurrent accessMultiple threadsConcurrent writes can cause incorrect results or lost updatesThreads can read and update safely using its methodsnull keys/valuesAllows one null key and multiple null valuesDoes not allow null keys or valuesTypical useSingle-threaded code or externally synchronized accessShared maps accessed by multiple threads</p><h3>Example</h3><pre>Map&lt;String, Integer&gt; counts = new HashMap&lt;&gt;();</pre><p>Use this when one thread owns the map, or when you provide synchronization yourself.</p><pre>Map&lt;String, Integer&gt; counts = new ConcurrentHashMap&lt;&gt;();</pre><p>Use this when multiple threads need to access or update the map concurrently.</p><p>For example, this operation is <strong>not atomic</strong> with a regular map:</p><pre>counts.put(key, counts.getOrDefault(key, 0) + 1);</pre><p>Two threads might read the same old value and overwrite each other’s updates. With ConcurrentHashMap, use its atomic merge method:</p><pre>counts.merge(key, 1, Integer::sum);</pre><p>That performs the update safely as one map operation.</p><p><strong>Rule of thumb:</strong> use HashMap when the map is not shared across threads. Use ConcurrentHashMap when it is shared and multiple threads may update it. A concurrent map makes its individual operations thread-safe; a sequence of separate operations may still need an atomic method such as merge() or compute().</p><h3>7. Why String is immutable; String vs. StringBuilder vs. StringBuffer</h3><h3>String vs. StringBuilder vs. StringBuffer</h3><p>TypeCan its contents change?Thread-safe?Best forStringNo; it’s immutableSafe to share because it cannot changeText that stays fixedStringBuilderYes; it’s mutableNoBuilding or changing text in one threadStringBufferYes; it’s mutableYes; its methods are synchronizedBuilding text shared across threads</p><h3>Example</h3><pre>String text = &quot;Hello&quot;;<br>text = text + &quot; World&quot;; // Creates a new String</pre><p>Repeatedly concatenating strings in a loop can create many temporary String objects. Use a StringBuilder for that:</p><pre>StringBuilder builder = new StringBuilder();</pre><pre>for (String word : words) {<br>    builder.append(word);<br>}</pre><pre>String result = builder.toString();</pre><p>StringBuffer has similar methods, but synchronizes them to make each method call thread-safe. That synchronization can add overhead. In most code, a StringBuilder is the usual choice when constructing text locally.</p><p><strong>Rule of thumb:</strong> use String for ordinary text, StringBuilder for repeated text changes, and StringBuffer only when you specifically need its synchronized methods.</p><h3>8. Garbage collection and memory leaks</h3><p><strong>Garbage collection (GC)</strong> is Java’s automatic process for reclaiming heap memory occupied by objects that are no longer reachable from the program’s live references.</p><p>You generally cannot force an object to be collected at a specific time. Calling System.gc() is only a request to the JVM.</p><p>Java can still have <strong>memory leaks</strong>. A leak occurs when the program keeps references to objects it no longer needs, so the GC considers them reachable and cannot reclaim them.</p><p>Common causes include:</p><ul><li>Static collections that keep accumulating entries.</li><li>Caches without limits or expiration.</li><li>Listeners or callbacks that are never removed.</li><li>Long-lived objects that retain large object graphs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d28c739c2f85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID]]></title>
            <link>https://medium.com/@gandharvdalal24/solid-d4f48eb61325?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f48eb61325</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 08:20:08 GMT</pubDate>
            <atom:updated>2026-10-25T08:20:08.463Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>S — Single Responsibility Principle</li></ol><pre>// A class should have one main responsibility, so it has one main reason to change.<br><br>//Problem: A Report class both creates report data and sends emails.<br><br>class Report {<br>    void generate() {<br>        // Create report<br>    }<br><br>    void sendEmail() {<br>        // Send report by email<br>    }<br>}<br><br>// If the email system changes, the report-generation class must change too.<br><br>// Improved design:<br>class Report {<br>    void generate() {<br>        // Create report<br>    }<br>}<br><br>class EmailService {<br>    void send(String message) {<br>        // Send email<br>    }<br>}</pre><p>2. O — Open/Closed Principle</p><pre>//Software components should be open for extension but closed for modification. You should be able to add behavior without repeatedly changing existing, working code.<br><br>//Problem: Adding a new discount type means adding another condition to this method.<br>class DiscountService {<br>    double applyDiscount(String type, double price) {<br>        if (type.equals(&quot;STUDENT&quot;)) {<br>            return price * 0.90;<br>        } else if (type.equals(&quot;SENIOR&quot;)) {<br>            return price * 0.80;<br>        }<br>        return price;<br>    }<br>}<br><br>//Improved design:<br>interface Discount {<br>    double apply(double price);<br>}<br><br>class StudentDiscount implements Discount {<br>    public double apply(double price) {<br>        return price * 0.90;<br>    }<br>}<br><br>class SeniorDiscount implements Discount {<br>    public double apply(double price) {<br>        return price * 0.80;<br>    }<br>}<br><br>class DiscountService {<br>    double applyDiscount(Discount discount, double price) {<br>        return discount.apply(price);<br>    }<br>}<br><br>//Now, adding a new discount means creating a new implementation rather than modifying DiscountService.</pre><p>3. L — Liskov Substitution Principle</p><pre>//An object of a child class should be usable wherever its parent type is expected without breaking the program’s expected behavior.<br><br>// Liskov Substitution Principle with birds<br>// Suppose we create a Bird class with a fly() method:<br><br>class Bird {<br>    void fly() {<br>        System.out.println(&quot;Flying&quot;);<br>    }<br>}<br><br>// A Sparrow can fly, so this works:<br><br>class Sparrow extends Bird {<br>}<br><br>// But a Penguin cannot fly. If it extends Bird, it has to inherit a behavior it cannot support:<br>class Penguin extends Bird {<br>    @Override<br>    void fly() {<br>        throw new UnsupportedOperationException(&quot;Penguins cannot fly&quot;);<br>    }<br>}<br><br>// Now imagine a method that expects every Bird to fly:<br>void makeBirdFly(Bird bird) {<br>    bird.fly();<br>}<br><br>// Calling makeBirdFly(new Penguin()) fails. The Penguin cannot safely replace Bird here, so this design violates LSP.<br>// Better design<br>// Put only shared behavior in Bird, and represent flying as a separate capability:<br>class Bird {<br>    void eat() {<br>        System.out.println(&quot;Eating&quot;);<br>    }<br>}<br><br>interface Flyable {<br>    void fly();<br>}<br><br>class Sparrow extends Bird implements Flyable {<br>    public void fly() {<br>        System.out.println(&quot;Sparrow is flying&quot;);<br>    }<br>}<br><br>class Penguin extends Bird {<br>    void swim() {<br>        System.out.println(&quot;Penguin is swimming&quot;);<br>    }<br>}<br><br>// Now a method that needs something that can fly accepts Flyable:<br>void makeFly(Flyable bird) {<br>    bird.fly();<br>}<br><br>// Sparrow can be passed to makeFly, while Penguin cannot—and no exception is needed.</pre><p>4. I — Interface Segregation Principle</p><pre>Clients should not be forced to depend on methods they do not use. Prefer small, focused interfaces over one large interface.<br><br>Problem: A basic printer is forced to implement scanning and faxing methods.<br><br>interface Machine {<br>    void print();<br>    void scan();<br>    void fax();<br>}<br><br>class BasicPrinter implements Machine {<br>    public void print() {<br>        // Print<br>    }<br><br>    public void scan() {<br>        throw new UnsupportedOperationException();<br>    }<br><br>    public void fax() {<br>        throw new UnsupportedOperationException();<br>    }<br>}<br><br>Improved design:<br>interface Printer {<br>    void print();<br>}<br><br>interface Scanner {<br>    void scan();<br>}<br><br>class BasicPrinter implements Printer {<br>    public void print() {<br>        // Print<br>    }<br>}<br><br>A multifunction machine can implement both Printer and Scanner.</pre><p>5. D — Dependency Inversion Principle</p><pre>High-level business logic should depend on abstractions, not directly on low-level implementation details. Both should depend on interfaces or other abstractions.<br><br>Problem: NotificationService is tightly coupled to email.<br>class EmailSender {<br>    void send(String message) {<br>        // Send email<br>    }<br>}<br><br>class NotificationService {<br>    private final EmailSender emailSender = new EmailSender();<br><br>    void notifyUser(String message) {<br>        emailSender.send(message);<br>    }<br>}<br><br>Changing from email to SMS requires changing NotificationService.<br><br>Improved design:<br><br><br>interface MessageSender {<br>    void send(String message);<br>}<br><br>class EmailSender implements MessageSender {<br>    public void send(String message) {<br>        // Send email<br>    }<br>}<br><br>class SmsSender implements MessageSender {<br>    public void send(String message) {<br>        // Send SMS<br>    }<br>}<br><br>class NotificationService {<br>    private final MessageSender messageSender;<br><br>    NotificationService(MessageSender messageSender) {<br>        this.messageSender = messageSender;<br>    }<br><br>    void notifyUser(String message) {<br>        messageSender.send(message);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f48eb61325" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monotonic stack]]></title>
            <link>https://medium.com/@gandharvdalal24/monotonic-stack-c9c80d12c4cc?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9c80d12c4cc</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 10:26:17 GMT</pubDate>
            <atom:updated>2026-10-11T10:26:17.188Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monotonic stack practice list</h3><pre>Rules:-<br><br>1. if we want to get nearest small number. Then pop when curr num is small than curr num.<br>2. When ever you are doing prefix sum start with 0 <br>{2,-1,2}<br>prefix sum []={0,2,1,3}<br>3.Normal sliding window negative numbers ke saath reliably work nahi karta. Isliye hum Prefix Sum + Monotonic Deque use karenge.</pre><pre>### 📝 Note: Substrings Containing an Index<br><br>For a string of length **`n`**, to find how many substrings contain the character at **index `i`**:<br><br>\[<br>\boxed{(i+1)\times(n-i)}<br>\]<br><br>**Easy way to remember:**<br><br>```text<br>Left choices × Right choices<br><br>(i + 1) × (n - i)<br><br><br>i - left + 1   = possible START points<br>right - i + 1  = possible END points<br><br><br>so our final formal is (i - left + 1)*(right - i + 1)<br>```<br><br>Example:<br><br>```text<br>s = &quot;abcde&quot;<br>     01234<br><br>For &#39;b&#39;:<br>i = 1<br>n = 5<br><br>Left choices  = i + 1 = 2<br>Right choices = n - i = 4<br><br>Total = 2 × 4 = 8<br>```<br><br>**Memory trick:**  <br>👉 **&quot;Start choices × End choices&quot;**<br><br>I’ll remember this formula for your future DSA discussions.</pre><h3>1. Next/previous greater or smaller element</h3><p>Learn how to maintain an increasing or decreasing stack, scan left-to-right or right-to-left, and decide when equal values should be popped.</p><ol><li><a href="https://leetcode.com/problems/next-greater-element-i/">Next Greater Element I — LeetCode 496</a> — next greater element; stack plus hash map. <em>Reported example: Amazon. — — → done</em></li><li><a href="https://leetcode.com/problems/next-greater-element-ii/">Next Greater Element II — LeetCode 503</a> — next greater in a circular array; simulate a second pass. ___&gt; done</li><li><a href="https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/">Final Prices With a Special Discount in a Shop — LeetCode 1475</a> — next smaller-or-equal element. → done</li><li><a href="https://leetcode.com/problems/next-greater-node-in-linked-list/">Next Greater Node In Linked List — LeetCode 1019</a> — next greater element when input comes from a linked list. → done</li></ol><h3>2. Waiting time and span</h3><p>Use the stack to find how far an element’s influence extends before a greater or smaller value blocks it.</p><ol><li><a href="https://leetcode.com/problems/daily-temperatures/">Daily Temperatures — LeetCode 739</a> — next warmer day and distance. <em>Reported examples: Amazon and Google. → done</em></li><li><a href="https://leetcode.com/problems/online-stock-span/">Online Stock Span — LeetCode 901</a> — previous greater element and accumulated span. __&gt; done</li><li><a href="https://leetcode.com/problems/steps-to-make-array-non-decreasing/">Steps to Make Array Non-decreasing — LeetCode 2289</a> — repeated removals and tracking how many rounds each element survives. → done</li><li><a href="https://leetcode.com/problems/number-of-visible-people-in-a-queue/">Number of Visible People in a Queue — LeetCode 1944</a> — visibility, popping blocked people, and counting the remaining blocker. → done</li></ol><h3>3. Nearest smaller boundaries and histogram areas</h3><p>Find the nearest smaller element on both sides. Those boundaries tell you how far a height or value can extend.</p><ol><li><a href="https://leetcode.com/problems/largest-rectangle-in-histogram/">Largest Rectangle in Histogram — LeetCode 84</a> — nearest smaller boundaries and maximum area. <em>Reported example: Waymo; company-tag listings vary. → done</em></li><li><a href="https://leetcode.com/problems/maximal-rectangle/">Maximal Rectangle — LeetCode 85</a> — convert each matrix row into a histogram and reuse the rectangle pattern. → done</li><li><a href="https://leetcode.com/problems/maximum-subarray-min-product/">Maximum Subarray Min-Product — LeetCode 1856</a> — nearest smaller boundaries plus prefix sums. → done</li><li><a href="https://leetcode.com/problems/maximum-score-of-a-good-subarray/">Maximum Score of a Good Subarray — LeetCode 1793</a> — expand around an index while tracking the limiting minimum. → done</li></ol><pre>we find the count of left and right smallest nearetst element.<br><br>to find thier index:-<br><br>int right=i+arr2[i]-1;<br>int left=i-arr1[i]+1;<br><br>and the formula to see how many indexs include them in combination:-<br>(i - left + 1) × (right - i + 1)</pre><h3>4. Contribution counting across subarrays</h3><p>Instead of evaluating every subarray, count how many subarrays use each element as their minimum or maximum. Pay attention to duplicates and strict versus non-strict comparisons.</p><ol><li><a href="https://leetcode.com/problems/sum-of-subarray-minimums/">Sum of Subarray Minimums — LeetCode 907</a> — count each element’s contribution as a minimum. → done</li><li><a href="https://leetcode.com/problems/sum-of-subarray-ranges/">Sum of Subarray Ranges — LeetCode 2104</a> — calculate maximum and minimum contributions, then subtract. → done</li><li><a href="https://leetcode.com/problems/sum-of-total-strength-of-wizards/">Sum of Total Strength of Wizards — LeetCode 2281</a> — contribution counting combined with prefix sums. → done</li><li><a href="https://leetcode.com/problems/number-of-valid-subarrays/">Number of Valid Subarrays — LeetCode 1063</a> — count subarrays whose first element is their minimum. →done</li></ol><h3>5. Greedy sequence construction</h3><p>Use the stack to remove earlier choices when a better later choice appears. This combines monotonicity with a greedy decision.</p><ol><li><a href="https://leetcode.com/problems/remove-k-digits/">Remove K Digits — LeetCode 402</a> — remove larger digits before smaller ones to form the smallest number. <em>Reported examples include Snap, PhonePe, and Coupang. →done</em></li><li><a href="https://leetcode.com/problems/find-the-most-competitive-subsequence/">Find the Most Competitive Subsequence — LeetCode 1673</a> — build the lexicographically smallest subsequence of a fixed length. → done</li><li><a href="https://leetcode.com/problems/remove-duplicate-letters/">Remove Duplicate Letters — LeetCode 316</a> — construct the smallest ordered result while keeping one of each character.</li><li><a href="https://leetcode.com/problems/create-maximum-number/">Create Maximum Number — LeetCode 321</a> — build best subsequences and merge them lexicographically.</li></ol><h3>6. Pattern detection and stack simulation</h3><p>These stretch the basic “find the next element” template into detecting a relationship or simulating interactions.</p><ol><li><a href="https://leetcode.com/problems/132-pattern/">132 Pattern — LeetCode 456</a> — detect a three-value pattern using a decreasing stack and a tracked middle value. → done</li><li><a href="https://leetcode.com/problems/asteroid-collision/">Asteroid Collision — LeetCode 735</a> — simulate directional collisions using a stack; not strictly monotonic, but valuable stack practice. → done</li><li><a href="https://leetcode.com/problems/car-fleet/">Car Fleet — LeetCode 853</a> — sort by position and use arrival times to identify merging fleets. It uses stack-style reasoning, though a stack may not be necessary. → done</li><li><a href="https://leetcode.com/problems/maximum-width-ramp/">Maximum Width Ramp — LeetCode 962</a> — build candidate indices with a decreasing stack, then scan to find the widest valid pair. → done</li></ol><h3>7. Monotonic deque: related, but a different structure</h3><p>A deque supports removing candidates from <strong>both ends</strong>. These problems share the monotonic idea, but don’t count them as stack-only practice.</p><ol><li><a href="https://leetcode.com/problems/sliding-window-maximum/">Sliding Window Maximum — LeetCode 239</a> — maintain the maximum candidate for each moving window. → done</li><li><a href="https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/">Shortest Subarray with Sum at Least K — LeetCode 862</a> — prefix sums plus a monotonic deque. → not done</li><li><a href="https://leetcode.com/problems/constrained-subsequence-sum/">Constrained Subsequence Sum — LeetCode 1425</a> — dynamic programming with a deque of useful previous states. _&gt; not done</li></ol><h3>Company examples</h3><p>For a few concrete examples, public interview reports list <strong>Daily Temperatures</strong> with Amazon and Google, <strong>Trapping Rain Water</strong> with Google, Amazon, and Microsoft, and <strong>Largest Rectangle in Histogram</strong> with Waymo. These are examples from community-maintained reporting, not official company question lists.</p><p>The full list above is organized by <strong>concept coverage</strong>, not by claimed company frequency. For your first pass, solve the first two problems in each section; then return for the remaining variations. <strong>Trapping Rain Water</strong> is also a valuable interview problem, but it’s often solved optimally with two pointers, so I haven’t counted it as a monotonic-stack-only question.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9c80d12c4cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DP:-]]></title>
            <link>https://medium.com/@gandharvdalal24/dp-b57ce800ceca?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/b57ce800ceca</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 16:23:23 GMT</pubDate>
            <atom:updated>2026-09-14T16:23:23.779Z</atom:updated>
            <content:encoded><![CDATA[<p>Imp :- <a href="https://leetcode.com/problems/longest-palindromic-substring/">5. Longest Palindromic Substring</a>. and <a href="https://leetcode.com/problems/palindromic-substrings/">647. Palindromic Substrings</a></p><p>Use expand from center approach</p><pre>class Solution {<br><br>    public String longestPalindrome(String s) {<br><br>        int start = 0;<br>        int maxLength = 1;<br><br>        for (int i = 0; i &lt; s.length(); i++) {<br><br>            // Odd length palindrome<br>            int len1 = expand(s, i, i);<br><br>            // Even length palindrome<br>            int len2 = expand(s, i, i + 1);<br><br>            int len = Math.max(len1, len2);<br><br>            if (len &gt; maxLength) {<br>                maxLength = len;<br>                start = i - (len - 1) / 2;<br>            }<br>        }<br><br>        return s.substring(start, start + maxLength);<br>    }<br><br>    private int expand(String s, int left, int right) {<br><br>        while (left &gt;= 0 &amp;&amp;<br>               right &lt; s.length() &amp;&amp;<br>               s.charAt(left) == s.charAt(right)) {<br><br>            left--;<br>            right++;<br>        }<br><br>        return right - left - 1;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b57ce800ceca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Pointers and Sliding window]]></title>
            <link>https://medium.com/@gandharvdalal24/two-pointers-and-sliding-window-8dad6afbcd96?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dad6afbcd96</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 11:18:29 GMT</pubDate>
            <atom:updated>2026-09-13T11:18:29.468Z</atom:updated>
            <content:encoded><![CDATA[<pre>set.put(fruits[right], map.getOrDefault(fruits[right], 0) + 1);</pre><p><a href="https://leetcode.com/problems/binary-subarrays-with-sum/">930. Binary Subarrays With Sum</a> and <a href="https://leetcode.com/problems/count-number-of-nice-subarrays/">1248. Count Number of Nice Subarrays</a>. and Subarray with k different integers</p><p>solve via atmost approach</p><pre>add()       → O(log n)<br>peek()      → O(1)<br>poll()      → O(log n)<br><br>remove(x)   → O(n)</pre><pre>// Only lowercase a-z<br>int[] freq = new int[26];<br>freq[ch - &#39;a&#39;]++;<br><br>// ASCII characters<br>int[] freq = new int[256];<br>freq[ch]++;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dad6afbcd96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LinkedList]]></title>
            <link>https://medium.com/@gandharvdalal24/linkedlist-2ded4286feca?source=rss-6c3d3f075b72------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ded4286feca</guid>
            <dc:creator><![CDATA[gandharv dalal]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 17:59:49 GMT</pubDate>
            <atom:updated>2026-09-10T17:59:49.730Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Floyd’s Cycle Detection</strong>.</p><p><a href="https://leetcode.com/problems/find-the-duplicate-number/"><strong>287. Find the Duplicate Number</strong></a></p><pre>class Solution {<br>    public int findDuplicate(int[] nums) {<br><br>        int slow = nums[0];<br>        int fast = nums[0];<br><br>        // Phase 1: Find intersection inside cycle<br>        do {<br>            slow = nums[slow];<br>            fast = nums[nums[fast]];<br>        } while (slow != fast);<br><br>        // Phase 2: Find cycle entry<br>        slow = nums[0];<br><br>        while (slow != fast) {<br>            slow = nums[slow];<br>            fast = nums[fast];<br>        }<br><br>        return slow;<br>    }<br>}</pre><p>// Note always use dummy where possible there might be cases where we need to change first position .</p><p>Question:- <a href="https://leetcode.com/problems/reverse-nodes-in-k-group/">25. Reverse Nodes in k-Group</a></p><pre>class Solution {<br>    public ListNode reverseKGroup(ListNode head, int k) {<br><br>        ListNode dummy = new ListNode(0);<br>        dummy.next = head;<br><br>        ListNode groupPrev = dummy;<br><br>        while (true) {<br><br>            ListNode kth = getKth(groupPrev, k);<br><br>            // Less than k nodes remaining<br>            if (kth == null) {<br>                break;<br>            }<br><br>            ListNode groupNext = kth.next;<br><br>            // Reverse current group<br>            ListNode prev = groupNext;<br>            ListNode curr = groupPrev.next;<br><br>            while (curr != groupNext) {<br><br>                ListNode next = curr.next;<br><br>                curr.next = prev;<br><br>                prev = curr;<br>                curr = next;<br>            }<br><br>            // groupPrev.next was old group head<br>            // After reversal it becomes group tail<br>            ListNode oldGroupHead = groupPrev.next;<br><br>            groupPrev.next = kth;<br><br>            groupPrev = oldGroupHead;<br>        }<br><br>        return dummy.next;<br>    }<br><br><br>    public ListNode getKth(ListNode curr, int k) {<br><br>        while (curr != null &amp;&amp; k &gt; 0) {<br>            curr = curr.next;<br>            k--;<br>        }<br><br>        return curr;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ded4286feca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>