<?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 Tejas S on Medium]]></title>
        <description><![CDATA[Stories by Tejas S on Medium]]></description>
        <link>https://medium.com/@tejassadashiva?source=rss-1b52eb892356------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1DsBIJ36nEX2VLfbcy09ww.png</url>
            <title>Stories by Tejas S on Medium</title>
            <link>https://medium.com/@tejassadashiva?source=rss-1b52eb892356------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:05:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tejassadashiva/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 Streams in Practice: Two Projects That Make It Click]]></title>
            <link>https://medium.com/@tejassadashiva/java-streams-in-practice-two-projects-that-make-it-click-df66e041c30a?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/df66e041c30a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java8-streams]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Mon, 04 May 2026 17:43:20 GMT</pubDate>
            <atom:updated>2026-05-04T17:43:20.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqSBCKDkU-nDcYPGR02qFg.png" /></figure><p>In part one of this series, we covered how streams work. The pipeline model, lazy evaluation, the six intermediate operations, the eight terminal operations, map vs flatMap, streams vs collections.</p><p>That was the theory.</p><p>This is where you actually use it.</p><p>The best way to internalize streams is to build something with them. Not toy examples with three numbers. Real programs where you can see the pipeline thinking replace the loop thinking.</p><p>Two projects. Built from scratch. Every line explained.</p><h3>Project 1: Word Frequency Counter</h3><p>You have a block of text. You want to know how many times each word appears, sorted from most frequent to least.</p><p>Simple goal. Interesting pipeline to get there.</p><h3>Think in stages first</h3><p>Before writing any code, map out what transformations the data needs.</p><pre>Raw text<br>  -&gt; split into individual words<br>  -&gt; lowercase everything<br>  -&gt; filter out empty strings<br>  -&gt; count how many times each word appears<br>  -&gt; sort by frequency, highest first<br>  -&gt; print</pre><p>Each arrow is a stream operation. Once you think this way, the code writes itself.</p><h3>Split and clean the text</h3><pre>String text = &quot;To be or not to be that is the question to be&quot;;<br><br>List&lt;String&gt; words = Arrays.stream(text.split(&quot;\\s+&quot;))<br>    .map(String::toLowerCase)<br>    .filter(word -&gt; !word.isEmpty())<br>    .collect(Collectors.toList());<br>// [to, be, or, not, to, be, that, is, the, question, to, be]</pre><p>\\s+ splits on one or more whitespace characters. It handles multiple spaces between words cleanly, which a simple &quot; &quot; split would not.</p><h3>Count the frequency of each word</h3><p>This is where groupingBy and counting come in. Two collectors working together.</p><pre>Map&lt;String, Long&gt; frequency = words.stream()<br>    .collect(Collectors.groupingBy(<br>        word -&gt; word,           // group key: the word itself<br>        Collectors.counting()   // value: how many in each group<br>    ));<br><br>// {be=3, to=3, or=1, not=1, that=1, is=1, the=1, question=1}</pre><p>groupingBy partitions the stream into groups. Every unique word becomes a key. counting() counts how many elements fell into each group. The result is a Map&lt;String, Long&gt; where each entry is a word paired with its count.</p><p>Order of the map entries is not guaranteed here. That is fine. You sort them in the next step.</p><h3>Sort by frequency and print</h3><pre>frequency.entrySet().stream()<br>    .sorted(Map.Entry.&lt;String, Long&gt;comparingByValue().reversed())<br>    .forEach(entry -&gt;<br>        System.out.printf(&quot;  %-12s -&gt; %d%n&quot;,<br>                entry.getKey(), entry.getValue())<br>    );</pre><p>Map.Entry.comparingByValue() sorts by count ascending. .reversed() flips it to descending. The type witness &lt;String, Long&gt; before comparingByValue() is needed because Java cannot always infer the generic types on static methods inside a chain.</p><h3>The full program</h3><pre>import java.util.*;<br>import java.util.stream.*;<br><br>public class WordFrequencyCounter {<br>    public static void main(String[] args) {<br>        String text = &quot;&quot;&quot;<br>                To be or not to be that is the question<br>                Whether tis nobler in the mind to suffer<br>                The slings and arrows of outrageous fortune<br>                Or to take arms against a sea of troubles<br>                &quot;&quot;&quot;;<br>        // Step 1: split, lowercase, clean<br>        List&lt;String&gt; words = Arrays.stream(text.split(&quot;\\s+&quot;))<br>                .map(String::toLowerCase)<br>                .filter(word -&gt; !word.isEmpty())<br>                .collect(Collectors.toList());<br>        // Step 2: count frequency of each word<br>        Map&lt;String, Long&gt; frequency = words.stream()<br>                .collect(Collectors.groupingBy(<br>                        word -&gt; word,<br>                        Collectors.counting()<br>                ));<br>        // Step 3: sort by frequency descending, print<br>        System.out.println(&quot;Word frequencies (most common first):\n&quot;);<br>        frequency.entrySet().stream()<br>                .sorted(Map.Entry.&lt;String, Long&gt;comparingByValue().reversed())<br>                .forEach(entry -&gt;<br>                        System.out.printf(&quot;  %-12s -&gt; %d%n&quot;,<br>                                entry.getKey(), entry.getValue())<br>                );<br>    }<br>}</pre><p>Output:</p><pre>Word frequencies (most common first):<br>  to           -&gt; 4<br>  the          -&gt; 2<br>  or           -&gt; 2<br>  of           -&gt; 2<br>  be           -&gt; 2<br>  not          -&gt; 1<br>  that         -&gt; 1<br>  is           -&gt; 1<br>  question     -&gt; 1<br>  ...</pre><h3>Two things to try yourself</h3><p><strong>Filter stop words.</strong> Words like “a”, “the”, “of”, “to” carry no meaning. Add a filter step to remove them before counting.</p><pre>Set&lt;String&gt; stopWords = Set.of(&quot;a&quot;, &quot;an&quot;, &quot;the&quot;, &quot;of&quot;, &quot;and&quot;, &quot;to&quot;, &quot;in&quot;, &quot;is&quot;, &quot;or&quot;);<br><br>List&lt;String&gt; words = Arrays.stream(text.split(&quot;\\s+&quot;))<br>        .map(String::toLowerCase)<br>        .filter(word -&gt; !word.isEmpty())<br>        .filter(word -&gt; !stopWords.contains(word))  // add this<br>        .collect(Collectors.toList());</pre><p><strong>Show only the top 5.</strong> Add .limit(5) after the sort. The pipeline stops after collecting five entries.</p><pre>frequency.entrySet().stream()<br>        .sorted(Map.Entry.&lt;String, Long&gt;comparingByValue().reversed())<br>        .limit(5)<br>        .forEach(...);</pre><h3>Project 2: Student Report Generator</h3><p>One dataset. Four reports. All streams.</p><p>You have a class of students. Each has a name, subject, and score. The goal is to generate different views of that data without writing a single manual loop.</p><h3>The data model</h3><pre>public record Student(String name, String subject, int score) {<br>    <br>    public String grade() {<br>        if (score &gt;= 90) return &quot;A&quot;;<br>        if (score &gt;= 80) return &quot;B&quot;;<br>        if (score &gt;= 70) return &quot;C&quot;;<br>        if (score &gt;= 60) return &quot;D&quot;;<br>        return &quot;F&quot;;<br>    }<br><br>    public boolean isPassing() {<br>        return score &gt;= 60;<br>    }<br>}</pre><p>record gives you a constructor, getters, equals, hashCode, and toString for free. grade() and isPassing() are computed from score so they do not need to be stored separately.</p><h3>The dataset</h3><pre>List&lt;Student&gt; students = List.of(<br>    new Student(&quot;Alice&quot;,   &quot;Math&quot;,    92),<br>    new Student(&quot;Bob&quot;,     &quot;Math&quot;,    58),<br>    new Student(&quot;Charlie&quot;, &quot;Science&quot;, 76),<br>    new Student(&quot;Diana&quot;,   &quot;Math&quot;,    88),<br>    new Student(&quot;Eve&quot;,     &quot;Science&quot;, 95),<br>    new Student(&quot;Frank&quot;,   &quot;English&quot;, 43),<br>    new Student(&quot;Grace&quot;,   &quot;English&quot;, 81),<br>    new Student(&quot;Henry&quot;,   &quot;Science&quot;, 67),<br>    new Student(&quot;Isla&quot;,    &quot;English&quot;, 73),<br>    new Student(&quot;Jack&quot;,    &quot;Math&quot;,    55)<br>);</pre><p>Ten students, three subjects, scores spread from failing to excellent.</p><h3>Report 1: who is passing?</h3><pre>students.stream()<br>    .filter(Student::isPassing)<br>    .map(Student::name)<br>    .sorted()<br>    .forEach(name -&gt; System.out.println(&quot;  &quot; + name));</pre><pre>Alice<br>Charlie<br>Diana<br>Eve<br>Grace<br>Henry<br>Isla</pre><p>Student::isPassing is a method reference. Shorthand for s -&gt; s.isPassing(). Use method references whenever the lambda does nothing except call one method. It reads more cleanly.</p><h3>Report 2: top performers with their grades</h3><pre>students.stream()<br>    .filter(s -&gt; s.score() &gt;= 80)<br>    .sorted(Comparator.comparingInt(Student::score).reversed())<br>    .map(s -&gt; String.format(&quot;  %-10s %-10s %d  (%s)&quot;,<br>            s.name(), s.subject(), s.score(), s.grade()))<br>    .forEach(System.out::println);</pre><pre>  Eve        Science    95  (A)<br>  Alice      Math       92  (A)<br>  Diana      Math       88  (B)<br>  Grace      English    81  (B)</pre><p>The shape of this pipeline comes up constantly in real code. Filter to narrow, sort to order, map to format, forEach to print. Learn this shape and you will reach for it instinctively.</p><h3>Report 3: average score per subject</h3><pre>students.stream()<br>    .collect(Collectors.groupingBy(<br>        Student::subject,<br>        Collectors.averagingInt(Student::score)<br>    ))<br>    .entrySet().stream()<br>    .sorted(Map.Entry.&lt;String, Double&gt;comparingByValue().reversed())<br>    .forEach(e -&gt; System.out.printf(&quot;  %-10s -&gt; %.1f%n&quot;,<br>            e.getKey(), e.getValue()));</pre><pre>  Science    -&gt; 79.3<br>  Math       -&gt; 73.3<br>  English    -&gt; 65.7</pre><p>groupingBy partitions students into subject buckets. averagingInt computes the average score inside each bucket. One stream operation gives you a complete subject breakdown.</p><h3>Report 4: full ranked list</h3><pre>List&lt;Student&gt; ranked = students.stream()<br>        .sorted(Comparator.comparingInt(Student::score).reversed())<br>        .collect(Collectors.toList());<br><br>for (int i = 0; i &lt; ranked.size(); i++) {<br>    Student s = ranked.get(i);<br>    System.out.printf(&quot;  %-4d %-10s %-10s %-6d %-5s %s%n&quot;,<br>            i + 1, s.name(), s.subject(),<br>            s.score(), s.grade(),<br>            s.isPassing() ? &quot;PASS&quot; : &quot;FAIL&quot;);<br>}</pre><pre>  1    Eve        Science    95     A     PASS<br>  2    Alice      Math       92     A     PASS<br>  3    Diana      Math       88     B     PASS<br>  4    Grace      English    81     B     PASS<br>  5    Charlie    Science    76     C     PASS<br>  6    Isla       English    73     C     PASS<br>  7    Henry      Science    67     D     PASS<br>  8    Bob        Math       58     F     FAIL<br>  9    Jack       Math       55     F     FAIL<br>  10   Frank      English    43     F     FAIL</pre><p>Streams do not have a built-in index. When you need position numbers, collect first and then loop with an index. That is not a limitation. It is the right tool for that specific job.</p><h3>What These Two Projects Share</h3><p>Both programs follow the same pattern.</p><p>Start with a collection. Open a stream. Express the transformation in plain language using filter, map, sorted, and collect. Read the result.</p><p>There is no loop management. No mutable accumulator. No tracking of where you are in the iteration. The intent of each step is on the surface.</p><p>That is the shift streams create. Once it clicks, writing imperative loops for data transformations starts to feel like the long way around.</p><h3>What Is Next</h3><p>These two projects cover the foundation. In the next part, we go deeper into Collectors: groupingBy, partitioningBy, joining, toMap, and how to combine them to express complex aggregations in a single statement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df66e041c30a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Streams: Part 1]]></title>
            <link>https://medium.com/@tejassadashiva/java-streams-part-1-8930ca2c4976?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/8930ca2c4976</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-stream-api]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java-development]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Sat, 02 May 2026 20:38:53 GMT</pubDate>
            <atom:updated>2026-05-02T20:38:53.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24ZgP1wBizJ9Dw2DxrvKtA.png" /></figure><h3>What They Are, How They Work, and Why They Click</h3><p>I used to write Java like this:</p><pre>List&lt;String&gt; result = new ArrayList&lt;&gt;();<br>for (String name : names) {<br>    if (name.length() &gt; 3) {<br>        result.add(name.toUpperCase());<br>    }<br>}</pre><p>It works. It always worked. So I never questioned it.</p><p>Then I saw someone solve the same problem in three lines using streams. I nodded like I understood. I did not understand. I just copied the pattern and moved on.</p><p>That worked until someone asked me to explain what flatMap does and why lazy evaluation matters. I had nothing.</p><p>So I went back and learned streams properly. This article is what I wish I had read then.</p><h3>The Problem Streams Actually Solve</h3><p>The loop above is called imperative code. You are telling Java exactly how to do things. Loop over this. Check this condition. Add to this list. You are the one managing every step.</p><p>Streams flip this. You tell Java what you want, not how to get it.</p><pre>List&lt;String&gt; result = names.stream()<br>    .filter(name -&gt; name.length() &gt; 3)<br>    .map(String::toUpperCase)<br>    .collect(Collectors.toList());</pre><p>Same output. The intent is right there on the surface. Filter long names, uppercase them, and collect the results. No loop management, no mutable list, no noise.</p><p>As operations stack up, this difference gets more and more significant.</p><h3>The Pipeline Mental Model</h3><p>Every stream has exactly three parts.</p><p><strong>Source.</strong> Where the data comes from. Usually a collection.</p><p><strong>Intermediate operations.</strong> Transformations that shape the data. filter, map, flatMap, sorted, distinct, peek. You can chain as many as you want.</p><p><strong>Terminal operation.</strong> The trigger that opens the tap and produces a result. collect, forEach, count, reduce, findFirst, anyMatch.</p><p>Think of it like water flowing through pipes. The tank holds your data. The pipes filter and reshape it. The bucket at the end collects the result.</p><p>The critical thing: <strong>water does not flow until you put a bucket at the end.</strong></p><h3>Nothing Runs Until You Ask For a Result</h3><p>This is lazy evaluation, and it trips up a lot of developers the first time.</p><pre>Stream&lt;String&gt; stream = names.stream()<br>    .filter(name -&gt; {<br>        System.out.println(&quot;Filtering: &quot; + name);<br>        return name.length() &gt; 3;<br>    });<br><br>System.out.println(&quot;Stream created. Nothing printed yet.&quot;);<br>// Output: Stream created. Nothing printed yet.<br><br>stream.collect(Collectors.toList());<br>// Now the println fires for each element</pre><p>Intermediate operations register intent. They build the recipe. Nothing cooks until a terminal operation fires.</p><p>This matters for performance. Java does not run filter on all elements and then run map on all survivors. It takes one element, runs it through the entire pipeline, then moves to the next. If the filter rejects an element, the map never sees it. This is called loop fusion.</p><h3>The Six Intermediate Operations</h3><p><strong>filter</strong> keeps elements that pass a test.</p><pre>names.stream()<br>    .filter(name -&gt; name.startsWith(&quot;A&quot;))<br>    // only names starting with A flow through</pre><p><strong>map</strong> transforms each element. One in, one out.</p><pre>names.stream()<br>    .map(String::toUpperCase)<br><br>// &quot;alice&quot; becomes &quot;ALICE&quot;</pre><p><strong>flatMap</strong> transforms each element into zero or more elements, then flattens everything into one stream.</p><pre>List&lt;String&gt; sentences = List.of(&quot;hello world&quot;, &quot;java streams&quot;);<br><br>sentences.stream()<br>    .flatMap(s -&gt; Arrays.stream(s.split(&quot; &quot;)))<br>    .collect(Collectors.toList());<br><br>// [&quot;hello&quot;, &quot;world&quot;, &quot;java&quot;, &quot;streams&quot;]</pre><p>Without flatMap, you would get a Stream of arrays. With flatMap, you get a single flat stream of words.</p><p><strong>distinct</strong> removes duplicates using equals().</p><p><strong>sorted</strong> orders elements. Natural order by default, or pass a Comparator.</p><p><strong>peek</strong> lets you observe each element mid-pipeline without changing it. Useful for debugging.</p><pre>.peek(n -&gt; System.out.println(&quot;After filter: &quot; + n))</pre><h3>map vs flatMap: The One That Confuses Everyone</h3><p>The rule is simple once you see it.</p><p>If your function returns a plain value, use map. If your function returns a Stream, List, or array and you want a flat result, use flatMap.</p><pre>// map: String -&gt; String (one to one)<br>names.stream().map(String::toUpperCase)<br><br>// flatMap: String -&gt; Stream&lt;String&gt; (one to many, then flattened)<br>orders.stream().flatMap(order -&gt; order.items().stream())</pre><p>The moment you see Stream&lt;List&lt;X&gt;&gt; in your IDE when you expected Stream&lt;X&gt;, switch to flatMap.</p><p>A real example. You have orders. Each order has a list of items. You want one flat list of all items.</p><pre>List&lt;String&gt; allItems = orders.stream()<br>    .flatMap(order -&gt; order.items().stream())<br>    .collect(Collectors.toList());</pre><p>One flatMap per level of nesting. Two levels deep? Two flatMaps.</p><h3>The Eight Terminal Operations</h3><p><strong>collect</strong> gathers elements into a container. Most versatile terminal op.</p><pre>.collect(Collectors.toList())<br>.collect(Collectors.joining(&quot;, &quot;, &quot;[&quot;, &quot;]&quot;))<br>.collect(Collectors.groupingBy(Employee::department))</pre><p><strong>forEach</strong> runs a side effect per element. Use it for printing or logging, not for building results.</p><p><strong>count</strong> returns how many elements survived the pipeline.</p><p><strong>reduce</strong> collapses everything into a single value.</p><pre>int sum = numbers.stream()<br>    .reduce(0, Integer::sum);<br>// Starts at 0, adds each element one by one</pre><p><strong>findFirst</strong> returns the first matching element as an Optional and stops immediately.</p><p><strong>findAny</strong> returns any matching element. Faster than findFirst in parallel streams.</p><p><strong>anyMatch</strong> returns true if at least one element passes. Stops at first match.</p><p><strong>allMatch</strong> returns true only if every element passes. Stops at first failure.</p><p>The last four are short-circuit operations. They do not need to see every element to give you an answer. This makes them significantly faster when working with large datasets.</p><h3>Streams vs Collections</h3><p>A Collection stores data. A Stream processes data.</p><p>Collection Stream Stores elements Yes No Reusable Yes No, single use Can be infinite No Yes Iteration External (you write the loop) Internal (stream handles it) Parallel Manual One method call</p><p>Once a terminal operation consumes a stream, it is closed. Call anything on it again and you get an IllegalStateException. Just call .stream() again on the collection.</p><p>Collections and streams are not competitors. The typical flow is: start with a collection, stream it, transform, collect back into a collection.</p><h3>Things to Remember</h3><p><strong>“What problem do streams solve?”</strong> They let you express data transformations declaratively instead of writing imperative loops. The intent is immediately readable and the code is composable.</p><p><strong>“What is lazy evaluation?”</strong> Intermediate operations do not execute when you call them. They register as steps in a pipeline. Everything runs when a terminal operation is called.</p><p><strong>“When do you use flatMap over map?”</strong> When your mapping function returns a collection, array, or stream and you want a flat result instead of a nested one.</p><p><strong>“What is the difference between findFirst and findAny?”</strong> findFirst guarantees the first element in encounter order. findAny is faster in parallel contexts because it returns whichever element any thread finds first.</p><p><strong>“Can streams be reused?”</strong> No. Once consumed by a terminal operation, a stream is closed. Create a new one from the source collection.</p><p>Streams clicked for me the moment I stopped thinking of them as a fancy loop and started thinking of them as a pipeline. Source, transformations, result. That is all they are.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8930ca2c4976" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Modules: The Java 9 Feature]]></title>
            <link>https://medium.com/@tejassadashiva/java-modules-the-java-9-feature-66908ac5e432?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/66908ac5e432</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Sat, 02 May 2026 14:33:57 GMT</pubDate>
            <atom:updated>2026-05-02T14:33:57.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZpN-4Jwqv5hSiNg31YjKg.png" /></figure><p>When I first heard “Java Module System,” I skipped it.</p><p>It felt like one of those topics you deal with someday. And someday never comes.</p><p>Then it showed up in an interview. I had nothing.</p><p>Once you understand the why, the what makes complete sense.</p><h3>The Problem It Solved</h3><p>Before Java 9, Java had three real problems.</p><p><strong>JAR Hell.</strong> A JAR is just a zip of compiled Java classes. Java loaded all your JARs into one flat bucket called the classpath. Two libraries using different versions of the same dependency? Java picks one silently. The other breaks at runtime. No error, no warning, just mysterious bugs at 2 AM.</p><p><strong>No real encapsulation.</strong> In Java, public means visible to everyone. When the JDK team wanted to mark something as internal, they had no tool to enforce it. They named packages sun.internal and wrote &quot;DO NOT USE&quot; in the docs. Developers used it anyway because nothing stopped them.</p><p><strong>Monolithic JDK.</strong> The entire JDK is shipped as one file calledrt.jar, about 65MB. Every Java app, even a Hello World, carried all of it. XML parsers, database drivers, and desktop UI libraries. All loaded, whether you used them or not.</p><p>Java 9 shipped the Module System in 2017 to fix all three.</p><h3>What Is a Module</h3><p>A module is a named unit of code that explicitly declares what it needs and what it shares.</p><p>Before modules, packages were like rooms in a building with no locks. Anyone could walk into any room. Modules add locks and a floor plan.</p><p>Every module has one file: module-info.java. It answers three questions.</p><pre>module com.myapp.core {<br>    exports com.myapp.core.api;   // what I share<br>    requires java.sql;            // what I need<br>}</pre><p>The JVM enforces this at both compile time and runtime. Not a convention. Enforced.</p><h3>The Two-Gate Rule</h3><p>Before modules, a public class had one gate:</p><pre>public -&gt; visible to everyone</pre><p>After modules, there are two gates:</p><pre>public  -&gt; visible within the module<br>exports -&gt; extends visibility across module boundaries</pre><p>A class can be public and still completely inaccessible to other modules if its package is not exported.</p><pre>// Inside calculator.engine module<br>package com.calc.internal;</pre><pre>public class SecretAlgorithm {   // public but package not exported<br>    public void compute() { }<br>}</pre><pre>// In another module<br>import com.calc.internal.SecretAlgorithm;  // COMPILE ERROR<br>// &quot;package com.calc.internal is not visible&quot;</pre><p>The library author finally has a real tool to enforce “internal means internal.”</p><h3>All the Keywords</h3><pre>module com.myapp {<br>    exports com.myapp.api;                        // everyone can see this<br>    exports com.myapp.secret to com.myapp.tests;  // only this module can see it<br><br>    requires java.sql;                            // I need this module<br>    requires transitive com.myapp.core;           // my dependents get this too<br>    requires static com.myapp.tools;              // compile-time only<br><br>    opens com.myapp.model;                        // allow reflection (Spring needs this)<br>    opens com.myapp.model to spring.core;         // reflection for one module only<br><br>    uses com.myapp.spi.PaymentGateway;            // I consume this service<br>    provides com.myapp.spi.PaymentGateway <br>          with com.myapp.StripeGateway;             // I provide this implementation<br><br>}</pre><h3>Things to remember</h3><p><strong>“What problem did modules solve?”</strong> JAR Hell, no real encapsulation, and a monolithic JDK that loaded everything even when unused.</p><p><strong>“What is module-info.java?”</strong> The module descriptor. Sits at the root of the source tree. Declares the module name, what it exports, and what it requires.</p><p><strong>“Can a public class be inaccessible?”</strong> Yes. Public gets you past gate one. Exports gets you past gate two. You need both for cross-module access.</p><p><strong>“Difference between exports and opens?”</strong> exports gives compile-time and runtime access. opens gives runtime reflection access only, which is what frameworks like Spring need internally.</p><p>The module system will not make your code run faster. But it gives Java something it never had before. Enforced architecture. The difference between “please don’t use this” in a comment and “you literally cannot use this” enforced by the compiler is not a small thing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66908ac5e432" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Replication: Why Your Database Needs a Backup Plan]]></title>
            <link>https://medium.com/@tejassadashiva/adatabase-replication-why-your-database-needs-a-backup-plan-7313a58ff9ff?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/7313a58ff9ff</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 04:31:02 GMT</pubDate>
            <atom:updated>2026-04-04T09:33:27.842Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into replication — for freshers, senior engineers, and everyone in between.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IINKkiBs7oCeY1zxXZN9cQ.png" /></figure><h3>Why Even Think About Replication?</h3><p>Let’s start with something simple. A database is just a server. And like any server, it has resource constraints — CPU, memory, disk I/O, and network bandwidth. There’s a ceiling to how much it can handle.</p><p>Now, imagine your application starts getting popular. Requests flood in. Reads, writes, complex queries — all at once. Your database starts to sweat. Eventually, it buckles under the load and goes down. Your entire application is now unavailable.</p><p>That’s the problem replication solves.</p><p>But before we get into the how, let’s understand the nature of these requests. A database typically handles two kinds:</p><ul><li><strong>Reads</strong> — fetching data</li><li><strong>Writes</strong> — inserting or updating data</li></ul><p>These two are fundamentally different. Reads are relatively cheap — you’re just retrieving data. Writes are expensive — they need to be durable, consistent, and safe. A database might comfortably handle ten thousand reads per second, but start struggling at just a few hundred complex writes per second.</p><p>For this article, let’s use a simple mental model: assume your database can handle <strong>1,000 reads per second</strong> and <strong>1,000 writes per second</strong>. That’s our capacity ceiling.</p><p>Now, what if you’re getting 3,000 reads per second? You’re in trouble. You need more capacity — specifically for reads. That’s where replication comes in.</p><h3>What Is Replication?</h3><p>Replication is the practice of maintaining <strong>multiple copies of your database</strong> across different servers.</p><p>One server is the <strong>primary</strong> (also called the master). It accepts all writes. The other servers are <strong>replicas</strong> (also called standbys or secondaries). They receive copies of those writes and can serve reads.</p><p>With three replicas, you’ve now effectively multiplied your read capacity. Those 3,000 reads per second can be distributed across replicas, while the primary focuses on writes.</p><p>But here’s the interesting bit — if your primary read capacity is now freed up, you can use it for additional writes. So replication doesn’t just scale reads; it indirectly gives your write path more breathing room, too.</p><p>There’s one more reason replication matters, and it’s arguably more important: <strong>availability</strong>.</p><p>What happens if your primary database crashes? If you have no replicas, your application goes down. Full stop. With replicas, one of them can be promoted to primary and take over. Your system survives the failure. That’s fault tolerance — and it’s why replication is non-negotiable for any serious production system.</p><h3>The Synchronisation Problem</h3><p>The moment you introduce multiple copies of your database, you face a new challenge: <strong>keeping them in sync</strong>.</p><p>When a write comes in to the primary, it needs to propagate to replicas. But how? And how quickly? And what guarantees do you need?</p><p>This is where three strategies emerge.</p><h3>1. Synchronous Replication</h3><p>In synchronous replication, the primary <strong>waits</strong> for all replicas to acknowledge a write before confirming it to the client. Only once every replica has the data does the primary respond with “success.”</p><p><strong>The good</strong>: You get <strong>strong consistency</strong>. At any point in time, all replicas have the same data. If the primary crashes, any replica can take over without data loss.</p><p><strong>The bad</strong>: <strong>Latency is high</strong>. Every write has to wait for the slowest replica to respond. If you have replicas across geographies, that round-trip time adds up. Under heavy write load, this becomes a serious bottleneck.</p><p><strong>When to use it</strong>: Financial systems, banking, anywhere where data loss is literally unacceptable. The latency cost is worth the guarantee.</p><h3>2. Asynchronous Replication</h3><p>In asynchronous replication, the primary writes locally, responds immediately to the client, and then propagates the write to replicas <strong>in the background</strong>.</p><p><strong>The good</strong>: <strong>Low latency</strong>. The client gets a response without waiting for any replica. Throughput is high.</p><p><strong>The bad</strong>: <strong>Data loss is possible</strong>. If the primary crashes before replicating a write, that write is gone forever. Also, reads from replicas might return stale data — a replica might not have caught up yet.</p><p>There’s a subtle but important problem here: <strong>read-your-own-writes</strong>. Imagine you write something to the primary, then immediately read it back. If your read goes to a replica that hasn’t received the write yet, you won’t see your own data. Frustrating and confusing.</p><p>One mitigation: route reads back to the primary until replication catches up. But that defeats the purpose of having replicas for reads.</p><p><strong>When to use it</strong>: Systems where some staleness is tolerable — social feeds, analytics dashboards, recommendation engines. Speed matters more than perfect consistency i.e If you need it to be eventually consistent, use it.</p><h3>The Sneak Peek Problem</h3><p>While a write is in-flight — being replicated to the quorum — there’s a window where some replicas have the new data, and some don’t. A read during this window might flip between seeing the new data and the old data, depending on which replica it hits. Disorienting for users. Hence, use Read-Your-Own-Writes as a solution.</p><h3>3. Quorum-Based Replication</h3><p>Quorum is the pragmatic middle ground. Instead of waiting for all replicas or none, you wait for a <strong>majority</strong> to acknowledge before committing.</p><p>With five servers, the majority is three. With three servers, the majority is two. The formula: (n/2) + 1.</p><p><strong>The good</strong>: You get durability without paying the full latency cost of synchronous replication. Even if some replicas are slow or temporarily unavailable, you can still commit writes and move on. It significantly reduces the data loss window compared to async.</p><p><strong>The bad</strong>: There are nuances — and they matter.</p><h3>Quorum’s Hidden Complexities</h3><p>Quorum sounds elegant. But there are real edge cases worth understanding.</p><h3>The Stale Read Problem</h3><p>Imagine you’ve written to a quorum of three out of five servers. Two servers are lagging. If a read request hits one of those two lagging servers, you get stale data. You read something that doesn’t reflect the latest write.</p><p>One way to handle this: always read from a majority of nodes and pick the freshest version using timestamps or version numbers. More overhead, but more accurate.</p><h3>Node Recovery and Stale Nodes</h3><p>When a node goes down and comes back up, it needs to sync itself to the current state. Until it does, any read hitting that node will return stale data. Proper replication systems handle this, but it’s a real operational concern.</p><h3>Data Loss Is Still Possible</h3><p>Here’s the edge case that surprises people: quorum doesn’t completely eliminate data loss.</p><p>Imagine five servers. A write is acknowledged by three (quorum). The primary then crashes. Those three servers are now part of the active cluster. But what if two of those three servers also fail before the write propagates to the remaining two?</p><p>You now have a cluster of three servers (the two that didn’t get the write, plus one recovered node) with no knowledge of that committed write. Data loss happens when the stale data node becomes the primary.</p><p>This is rare, but it can happen. That’s why quorum gives you <strong>eventual consistency with strong durability guarantees</strong> — but not strong consistency in the absolute sense. For guarantees, you need synchronous replication.</p><h3>Quorum and Availability</h3><p>One more thing: a quorum needs a minimum number of nodes to function. If too many nodes go down and you can’t reach a majority, writes will fail entirely. You’re trading some availability for durability.</p><h3>Choosing Between Sync, Async, and Quorum</h3><p>Here’s a simple decision framework:</p><p>Situation Use Financial system, no data loss tolerable — Synchronous High-read system, some staleness okay — Async Need durability but can’t afford full sync latency and for balanced — Quorum.</p><h3>Master-Standby Architecture</h3><p>For most systems, the right architecture is <strong>master-standby</strong>.</p><p>One primary accepts all writes. One or more standbys replicate those writes and serve reads. A cluster manager monitors health, detects primary failure, and promotes the most up-to-date standby as the new primary.</p><p>The promotion involves leader election — nodes vote, or the system picks the standby with the latest data. This is handled by the database software (PostgreSQL, MySQL, etc.) — you don’t build this yourself.</p><p>This architecture is simple, conflict-free, and well-understood. Writes go to one place. No ambiguity. No conflicts.</p><p>The limitation: <strong>writes don’t scale</strong>. All writes go to the primary. If writes become your bottleneck, master-standby alone won’t save you. (That’s a topic for a separate article on sharding and partitioning.)</p><h3>How Does a Client Know Where to Connect?</h3><p>Here’s a question that doesn’t get asked enough: you’ve got a primary and two standbys — who does your application actually talk to?</p><p>The answer is almost never “the application connects directly to a specific database server.” That would be fragile — if the primary goes down and a standby takes over, your application would be pointing at the wrong server and have no idea.</p><p>Instead, there’s typically an abstraction layer sitting between your application and the database cluster. A few common approaches:</p><p><strong>Connection Pooler / Proxy</strong> — Tools like PgBouncer, ProxySQL, or HAProxy sit in front of your cluster. Your application connects to the proxy, not the database directly. The proxy inspects each query — is it a write? Route to primary. Is it a read? Route to a replica. The application is completely unaware of the underlying topology. This is the most common pattern in production.</p><p><strong>DNS-based routing</strong> — The cluster exposes a single DNS name (say, db.myapp.com). Internally, this DNS resolves to the current primary. When a failover happens and a standby gets promoted, the DNS record is updated to point to the new primary. Clients reconnect and land on the right server automatically. Simple, but there&#39;s a propagation delay while DNS updates.</p><p><strong>Smart client drivers</strong> — Some databases build this routing logic into their official drivers. MongoDB drivers, for instance, are cluster-aware — they discover the topology automatically and route writes to the primary and reads to secondaries without you configuring anything. Cassandra drivers do the same with consistent hashing. Your application just connects to “the cluster” and the driver figures out the rest.</p><p><strong>Service discovery in cloud environments</strong> — In Kubernetes or AWS RDS, a managed service sits in front of your database cluster. AWS Aurora, for example, provides separate endpoints for writes and reads. You connect your application to writer.cluster.rds.amazonaws.com for writes and reader.cluster.rds.amazonaws.com for reads. The cloud provider handles everything underneath.</p><h3>What Happens During Failover?</h3><p>This is where it gets interesting. When the primary goes down, the cluster needs to elect a new primary from the standbys. During this election — which typically takes a few seconds to a minute depending on the system — writes will fail. There is always a brief window of unavailability.</p><p>Once the new primary is elected, the proxy or DNS layer detects the change and reroutes traffic. Your application might see a few failed requests during this window, which is why building retry logic into your application is important.</p><p>The key insight: <strong>the routing layer is what makes replication transparent to your application</strong>. Without it, every client would need to know the cluster topology and handle failovers themselves. That’s not scalable. The proxy or smart driver handles it so your application doesn’t have to.</p><h3>What About Multi-Master?</h3><p>Multi-master (or active-active) architecture allows multiple nodes to accept writes simultaneously. Sounds powerful — and it is. But it comes with serious complexity.</p><p>When two nodes accept concurrent writes to the same row, which one wins? You need <strong>conflict resolution</strong>:</p><ul><li><strong>Last-write-wins</strong> (based on timestamps): Simple, but you lose history. The earlier write is silently discarded.</li><li><strong>Version-based</strong>: Track versions, but merging conflicts still requires logic.</li><li><strong>CRDTs</strong> (Conflict-free Replicated Data Types): Mathematically designed data structures that merge automatically. Elegant but complex to implement and not suitable for all data models.</li></ul><p>In practice, most systems avoid multi-master unless they genuinely need write scalability across geographies. The conflict resolution overhead is significant, and the operational complexity is high. If you need to scale writes, we will discuss it in another article.</p><h3>How Data Gets Replicated: The Mechanics</h3><p>When the primary writes data, how does that change travel to replicas? There are a few approaches:</p><p><strong>Statement-based replication</strong>: The SQL statement itself is sent to replicas and re-executed. Simple, but fragile — different database versions, non-deterministic functions (like NOW()), or statement order or auto-increments can produce different results on different replicas.</p><p><strong>Row-based replication</strong>: Instead of the statement, the actual row changes are sent. More reliable, but verbose — a single update affecting millions of rows sends millions of row changes. In this case, when we get writes concurrently, we may have to go with Last-Write-Wins or version-based or timestamp-based, but we lose the history of updates/writes.</p><p><strong>Change Data Capture (CDC)</strong>: As the primary processes write, changes are streamed out to a queue or event log in real-time. Replicas (or downstream consumers) process this stream. This is increasingly popular because it decouples replication from the database internals and enables powerful event-driven architectures. It’s reliable, preserves history, and plays well with modern data pipelines.</p><h3>Availability: The Other Reason for Replication</h3><p>We started with scaling. But availability is equally important.</p><p>A single database is a <strong>single point of failure</strong>. Replication eliminates that. With a standby ready to take over, your system can survive a primary failure with minimal downtime.</p><p>The combination of read scaling and fault tolerance is what makes replication indispensable for production systems.</p><h3>Summary</h3><p>Database replication is fundamentally about two things: <strong>scaling reads</strong> and <strong>ensuring availability</strong>.</p><ul><li><strong>Synchronous</strong> gives you strong consistency at the cost of latency — use it where data loss is unacceptable.</li><li><strong>Asynchronous</strong> gives you low latency at the risk of data loss and stale reads — use it where eventual consistency is fine.</li><li><strong>Quorum</strong> balances durability and latency — the pragmatic choice for most systems, but with its own edge cases around stale reads and rare data loss scenarios.</li><li>There are a couple of strategies when moving from sync to async, based on the WAL log, where it has to be present, like in primary or standby, so that at each point we can set up the replication mechanisms, and when to make sure to respond to the request.</li><li><strong>Master-standby</strong> is the right architecture for most use cases — simple, conflict-free, with writes centralised on the primary.</li><li><strong>Multi-master</strong> is powerful but complex — reserved for specific use cases where write locality across regions is a hard requirement.</li></ul><p>The goal isn’t to memorise these trade-offs. It’s to reason about them. When you understand why each approach exists and what problem it solves, choosing the right one for your system becomes intuitive.</p><p><em>Next up: When reads are scaled and writes become the bottleneck — a deep dive into sharding and partitioning.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7313a58ff9ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST Explained — Why Resource Modeling Changes Everything (Part 3)]]></title>
            <link>https://medium.com/@tejassadashiva/rest-explained-why-resource-modeling-changes-everything-part-3-9db21d338ed4?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/9db21d338ed4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 17:08:44 GMT</pubDate>
            <atom:updated>2026-02-27T17:08:44.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WH8sK8H687bAH3yj5941fg.png" /></figure><blockquote>Part 1: <a href="https://medium.com/@tejassadashiva/why-apis-exist-a-guide-for-software-engineers-part-1-fe363656b387">Why APIs Exist — A Guide for Software Engineers</a></blockquote><blockquote>Part 2: <a href="https://medium.com/@tejassadashiva/http-from-scratch-what-actually-travels-over-the-network-part-2-b2a9b3e7c7a0">HTTP From Scratch — What Actually Travels Over the Network</a></blockquote><p>Most REST tutorials start with:</p><p>“Here’s how to build a CRUD API in Spring Boot.”</p><p>But very few explain:</p><p>Why does REST exist at all?<br>Why does it feel so natural once you understand HTTP?</p><h3>A Brief History of REST</h3><p>REST (Representational State Transfer) was popularized by <strong>Roy Fielding</strong> in his 2000 doctoral dissertation.</p><p>Fielding was one of the principal authors of the HTTP specification.<br> Instead of inventing a new protocol, REST proposed something more elegant:</p><blockquote><em>Use the existing semantics of HTTP correctly.</em></blockquote><p>REST is not a protocol.<br>It is an architectural style for designing distributed systems.</p><p>It embraces the web’s original design principles rather than replacing them.</p><p>That is why REST feels natural once you understand HTTP.</p><h3>The Problem REST Solves</h3><p>Before REST became dominant, many systems exposed functionality like this:</p><pre>POST /createUser<br>POST /deleteUser<br>POST /updateUserName<br>POST /getUserDetails</pre><p>This is essentially exposing functions over the network.</p><p>It tightly couples clients to server-side behavior.<br>It treats the network like a remote method call system.</p><p>That approach does not scale well — conceptually or architecturally.</p><p>REST introduced a shift in thinking.</p><p>Stop thinking in actions.<br>Start thinking in resources.</p><h3>What Is a Resource?</h3><p>A resource is a noun representing something in your domain.</p><p>Examples:</p><ul><li>User</li><li>Course</li><li>Candidate</li><li>Ticket</li></ul><p>Not:</p><ul><li>createUser</li><li>deleteInterview</li><li>runEvaluation</li></ul><p>Resources represent the state.<br>HTTP methods represent operations on that state.</p><p>This is the core design shift.</p><h3>Why REST Feels Natural After Understanding HTTP</h3><p>In Part 2, we saw that HTTP already gives us verbs:</p><blockquote>GET, POST, PUT, PATCH, DELETE</blockquote><p>REST combines: HTTP verbs + Resource nouns</p><p>Instead of this:</p><pre>POST /createCourse<br>POST /deleteCourse</pre><p>We design this:</p><pre>POST /courses<br>GET /courses/42<br>PUT /courses/42<br>DELETE /courses/42</pre><p>Now:</p><ul><li>The URL identifies the resource.</li><li>The HTTP method identifies the action.</li></ul><p>Clean separation of responsibility.</p><h3>Statelessness — The Scalability Enabler</h3><p>REST requires stateless communication.</p><p>Each request must contain everything needed to process it.</p><p>Why?</p><p>Because HTTP itself is stateless.</p><p>If the server depended on previous requests or hidden session memory, horizontal scaling would become complex.</p><p>Stateless design allows:</p><ul><li>Load balancing</li><li>Independent server instances</li><li>Resilience</li><li>Easier fault recovery</li></ul><p>When one server fails, another can process the same request without shared memory.</p><p>This is foundational for modern distributed systems.</p><h3>Uniform Interface — The Hidden Power</h3><p>One of the most important REST constraints is the uniform interface.</p><p>It means:</p><p>All resources are accessed and manipulated consistently.</p><p>Every resource:</p><ul><li>Can be retrieved with GET</li><li>Updated with PUT or PATCH</li><li>Deleted with DELETE</li></ul><p>Clients do not need special logic for each endpoint.</p><p>Once a client understands the pattern, they can navigate the system predictably. This is more like you have been given the directional instructions to navigate a building; now it is your responsibility to explore the building using the instructions.</p><h3>Resource Identification via URL</h3><p>In REST, the URL identifies the resource.</p><p>Examples:</p><pre>GET /courses<br>GET /courses/42<br>GET /courses/42/modules<br>GET /courses/42/modules/3</pre><p>Notice the hierarchy.</p><blockquote>Module 3 belongs to Course 42.</blockquote><p>URLs should reflect domain ownership and relationships.</p><p>Good REST design mirrors your domain model.</p><h3>Representation — You Don’t Send the Resource Itself</h3><p>When you retrieve a resource, you don’t get the actual object from memory.</p><p>You get a representation.</p><p>Example JSON representation of a Course:</p><pre>{<br>  &quot;id&quot;: 42,<br>  &quot;title&quot;: &quot;Backend Engineering&quot;,<br>  &quot;level&quot;: &quot;Advanced&quot;<br>}</pre><p>This is a representation of the resource state.</p><p>The same resource could be represented as:</p><ul><li>XML</li><li>HTML</li></ul><p>That is why the <strong><em>Accept</em></strong> and <strong><em>Content-Type </em></strong>headers exist.</p><h4>REST separates:</h4><p>Resource identity (URL)<br>Resource representation (JSON/XML/etc.)</p><h3>A few more REST constraints</h3><h4>Client–Server</h4><p>The client and server are separated.</p><ul><li>The client handles the user interface.</li><li>The server manages data and business logic.</li></ul><p>This separation allows independent evolution and scalability.</p><h4>Cacheable</h4><p>Responses must define whether they are cacheable.</p><p>Proper caching:</p><ul><li>Reduces server load</li><li>Improves performance</li><li>Enhances scalability</li></ul><p>HTTP headers like Cache-Control and ETag enable this.</p><h4>Layered System</h4><p>Clients should not need to know whether they are connected directly to the server or through intermediaries.</p><p>There may be:</p><ul><li>Proxies</li><li>Gateways</li><li>Load balancers</li><li>Caching layers</li></ul><p>This abstraction improves flexibility and scalability.</p><h4>Code on Demand (Optional)</h4><p>Servers may optionally send executable code to clients.</p><p>For example:</p><ul><li>JavaScript in browsers</li></ul><p>This constraint is rarely emphasized in API design but is part of the original REST definition.</p><h3>Applying REST to an AI Interview System</h3><p>Let’s model a real domain.</p><p>Resources:</p><ul><li>Candidate</li><li>Interview</li><li>Question</li><li>Response</li><li>Evaluation</li></ul><p>Good REST endpoints might look like:</p><pre>GET /candidates<br>POST /candidates<br>GET /candidates/{id}<br><br>POST /candidates/{id}/interviews<br>GET /interviews/{id}<br><br>POST /interviews/{id}/responses<br>GET /interviews/{id}/evaluation</pre><p>Even without documentation, intent is clear.</p><p>That clarity is the hallmark of good REST design.</p><h3>Common REST Mistakes</h3><ul><li>Using verbs in URLs:</li></ul><blockquote>POST /createInterview</blockquote><ul><li>Overusing POST for everything.</li><li>Using GET for state-changing operations.</li><li>Ignoring idempotency semantics.</li></ul><p>REST is not about CRUD.<br>It is about modeling your domain as resources and using HTTP semantics correctly.</p><h3>The Core Mental Model</h3><p>Think of REST as:</p><p>Domain → Resource<br>Operation → HTTP method<br>Data → Representation</p><p>REST is not a protocol.<br>It is a disciplined way of using HTTP.</p><h3>In the Next Article</h3><p>We go deeper into:</p><blockquote>HTTP Methods — Idempotency, Safety, and Real-World Design Tradeoffs</blockquote><p>Because true REST mastery requires understanding how methods behave under retries, failures, and distributed systems.</p><p>Part of the Backend Engineering Series.<br>Foundations first. Frameworks later.</p><p>If you liked this article, clap ❤️ and follow for the next part!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9db21d338ed4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP From Scratch — What Actually Travels Over the Network (Part 2)]]></title>
            <link>https://medium.com/@tejassadashiva/http-from-scratch-what-actually-travels-over-the-network-part-2-b2a9b3e7c7a0?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2a9b3e7c7a0</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 19:07:33 GMT</pubDate>
            <atom:updated>2026-02-26T19:15:36.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npeCyNBC5WKuf4HuSqTeVw.png" /></figure><p>Most engineers use HTTP every day. Very few understand what actually travels over the network.</p><blockquote>This article is a continuation of <a href="https://medium.com/@tejassadashiva/why-apis-exist-a-guide-for-software-engineers-part-1-fe363656b387">Why APIs exist? (Part 1)</a></blockquote><p>Frameworks abstract it.<br>Browsers hide it.<br>Libraries simplify it.</p><p>But underneath all that abstraction is something surprisingly simple:</p><blockquote><em>HTTP is just structured text sent as bytes over a TCP connection.</em></blockquote><p>If you truly understand this, REST stops feeling magical and starts feeling obvious.</p><h3>The Fundamental Question</h3><p>When your frontend sends:</p><pre>POST /courses</pre><p>What actually happens?</p><p>Not Java objects.<br>Not JSON objects.<br>Not Spring Boot controllers.</p><p>Just <strong>bytes over a network socket.</strong></p><h3>HTTP Is a Text-Based Protocol</h3><p>HTTP is a:</p><ul><li>Stateless</li><li>Request–response</li><li>Text-based protocol</li><li>Built on top of TCP</li></ul><p>“Text-based” does not mean “not binary.”</p><p>It means:</p><blockquote><em>The bytes represent readable characters (usually UTF-8).</em></blockquote><p>Everything over the network is ultimately just bytes.</p><h3>Anatomy of an HTTP Request</h3><p>Let’s write one manually.</p><pre>POST /courses HTTP/1.1<br>Host: api.tejas.com<br>Authorization: Bearer &lt;token&gt;<br>Content-Type: application/json<br>Accept: application/json<br><br>{<br>  &quot;title&quot;: &quot;Backend Engineering&quot;,<br>  &quot;level&quot;: &quot;Advanced&quot;,<br>  &quot;durationInHours&quot;: 20<br>}</pre><p>Now let’s break this down.</p><h3>1. Request Line</h3><pre>POST /courses HTTP/1.1</pre><p>It contains:</p><ul><li>Method (POST)</li><li>Path (/courses)</li><li>Protocol version (HTTP/1.1)</li></ul><p>This line tells the server:</p><blockquote><em>What action? On what resource? Using what protocol?</em></blockquote><h3>2. Headers</h3><pre>Host: api.tejas.com<br>Authorization: Bearer &lt;token&gt;<br>Content-Type: application/json<br>Accept: application/json</pre><p>Headers are metadata.</p><p>They describe how the request should be interpreted.</p><p>Examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyU8hYlpqzDmvlWhauaZCw.png" /></figure><p>Headers keep contextual information separate from the actual resource data.</p><p>This separation is intentional and powerful.</p><h3>3. Body</h3><p>Everything after the blank line is the body.</p><pre>{<br>  &quot;title&quot;: &quot;Backend Engineering&quot;,<br>  &quot;level&quot;: &quot;Advanced&quot;,<br>  &quot;durationInHours&quot;: 20<br>}</pre><p>This is the actual payload.</p><p>For POST, PUT, PATCH — the body carries the resource data.</p><h3>Why Do We Need the Content-Type Header?</h3><p>Here’s a deeper question:</p><p>Why can’t the server just “figure out” the format?</p><p>Because the server receives:</p><blockquote><em>A stream of bytes.</em></blockquote><p>It does not know whether those bytes represent:</p><ul><li>JSON</li><li>XML</li><li>Form data</li><li>Plain text</li><li>An image</li><li>A binary file</li></ul><p>These two bodies represent the same logical information:</p><p>JSON:</p><pre>{ &quot;name&quot;: &quot;Tejas&quot; }</pre><p>Form URL Encoded:</p><pre>name=Tejas</pre><p>Has completely different formats.</p><p>So we must explicitly tell the server:</p><pre>Content-Type: application/json</pre><p>This tells the server:</p><blockquote><em>Use a JSON parser to interpret these bytes.</em></blockquote><p>Without it, parsing would be ambiguous and unsafe.</p><h3>Is JSON a Text or Binary?</h3><p>A subtle but important question:</p><blockquote><em>JSON is text-based… but doesn’t the network send binary?</em></blockquote><p>Correct.</p><p>Everything sent over TCP is bytes.</p><p>When we say “HTTP is text-based,” we mean:</p><ul><li>The protocol messages are human-readable</li><li>The bytes correspond to characters (ASCII / UTF-8)</li></ul><p>Example:</p><p>The string:</p><pre>GET /users HTTP/1.1<br>.....</pre><p>Is sent as bytes representing those characters.</p><h3>The Full Flow: Serialization &amp; Encoding</h3><p>Let’s trace what actually happens.</p><h3>On the Frontend:</h3><ol><li>JavaScript object</li><li>Serialized to a JSON string</li><li>Encoded into UTF-8 bytes</li><li>Sent over TCP</li></ol><h3>On the Backend:</h3><ol><li>Receives raw bytes</li><li>Decodes UTF-8 into text</li><li>Parses JSON</li><li>Converts into a Java object</li></ol><p>This is the real pipeline:</p><p>Object → JSON text → Bytes → Network → Bytes → JSON text → Object</p><p>Understanding this pipeline is critical for debugging and system design.</p><h3>Why This Matters in Real Engineering</h3><p>This knowledge helps you understand:</p><ul><li>Encoding bugs</li><li>Unicode issues</li><li>File uploads</li><li>Content negotiation</li><li>Proxy behavior</li><li>Caching systems</li><li>Performance trade-offs</li></ul><h3>Text Protocols vs Binary Protocols</h3><p>HTTP + JSON are text-based.</p><p>Advantages:</p><ul><li>Human-readable</li><li>Easy debugging</li><li>Flexible</li><li>Universally supported</li></ul><p>Disadvantages:</p><ul><li>Larger payload size</li><li>Slightly slower parsing</li></ul><p>Binary protocols like Protobuf (used in gRPC):</p><p>Advantages:</p><ul><li>Smaller payload</li><li>Faster serialization/deserialization</li></ul><p>Disadvantages:</p><ul><li>Harder to inspect</li><li>Less flexible without a schema</li></ul><p>This is an engineering tradeoff — not a “better vs worse” situation.</p><h3>Key Takeaways</h3><ul><li>HTTP is a stateless request-response protocol.</li><li>Everything sent over the network is bytes.</li><li>“Text-based” means bytes representing readable characters.</li><li>Content-Type tells the server how to parse the body.</li><li>Serialization and encoding are separate concepts.</li><li>Understanding raw HTTP improves debugging and architecture skills.</li></ul><h3>In the Next Article</h3><p>We move one layer up:</p><p><strong>REST Principles — Why REST Feels Natural Once HTTP Is Understood</strong></p><p>Because once you understand the transport, the architectural design becomes inevitable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2a9b3e7c7a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why APIs Exist — A Guide for Software Engineers (Part 1)]]></title>
            <link>https://medium.com/@tejassadashiva/why-apis-exist-a-guide-for-software-engineers-part-1-fe363656b387?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe363656b387</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 16:47:21 GMT</pubDate>
            <atom:updated>2026-02-26T16:47:21.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPyXgoUbbuZo-dQeDU7GaQ.png" /></figure><p>Most tutorials on APIs begin with frameworks, code snippets, or “How to build a REST API in Spring Boot or using any framework.”</p><p>But very few answer the most important question:</p><blockquote><strong><em>Why do APIs exist at all?</em></strong></blockquote><p>If you understand this from first principles, everything else — REST, HTTP methods, authentication, pagination — starts making intuitive sense.</p><h3>The Fundamental Problem</h3><p>Before REST.<br>Before HTTP.<br>Before JSON.</p><p>There was only this problem:</p><p><strong>How do two independent software systems communicate?</strong></p><p>Not modules inside the same codebase.<br>Not classes in the same program.</p><p>But:</p><ul><li>Programs on different machines</li><li>Written in different languages</li><li>Owned by different teams</li><li>Evolving at different speeds</li></ul><p>For example, consider a modern application:</p><ul><li>A React frontend</li><li>A backend service</li><li>An AI evaluation service</li><li>A database</li></ul><p>Each of these is an independent system.</p><p>They must exchange information without knowing each other’s internal implementation.</p><h3>Why Direct Coupling Fails</h3><p>In early software, communication often meant directly calling another program’s code or sharing internal data structures.</p><p>This approach fails when:</p><ul><li>Systems are deployed separately</li><li>Teams release changes independently</li><li>Technologies differ</li><li>Network boundaries exist</li></ul><p>Tight coupling creates fragile systems.</p><p>A small change in one system can break another.</p><h3>Loose Coupling — The Real Goal</h3><p>Successful large-scale systems rely on <strong>loose coupling</strong>.</p><p>Loose coupling means:</p><ul><li>Systems interact through well-defined interfaces</li><li>Internal changes do not break external users</li><li>Each system can evolve independently</li></ul><p>Think of two companies communicating via a standardized form (say Email) instead of sharing internal documents.</p><p>As long as the form stays consistent, both sides can change internally.</p><h3>APIs Are Contracts</h3><blockquote><strong><em>An API is a contract that defines how independent systems communicate over a network.</em></strong></blockquote><p>The contract specifies:</p><ul><li>What you can request</li><li>How to make the request</li><li>What response will you receive</li></ul><p>Crucially, it hides implementation details.</p><p>The client does not need to know:</p><ul><li>Which database is used</li><li>What algorithms run internally</li><li>How the service is structured</li></ul><p>This separation enables scalability and team autonomy.</p><h3>Why Network Communication Needs Standards</h3><p>Once systems communicate over a network, three things are required:</p><h3>1. A Transport Mechanism</h3><p>How data moves between systems<br>→ HTTP</p><h3>2. A Data Format</h3><p>How information is structured<br>→ JSON, XML, etc.</p><h3>3. Communication Rules</h3><p>How requests and responses behave<br>→ REST principles</p><p>APIs bring all three together.</p><h3>External APIs vs Internal APIs</h3><p>When people think of APIs, they often imagine frontend-to-backend communication.</p><p>But APIs also exist between internal services.</p><p>Example flow for submitting an interview response:</p><ol><li>Frontend sends a response to the backend</li><li>Backend calls the AI evaluation service</li><li>AI service returns evaluation</li><li>Backend stores results in the database</li><li>Backend sends feedback to frontend</li></ol><p>Every step involves APIs.</p><p>APIs are the glue of distributed systems.</p><h3>The Real Purpose of APIs</h3><p>APIs enable:</p><ul><li>Separation of concerns</li><li>Independent deployment</li><li>Technology diversity</li><li>Horizontal scaling</li><li>Team autonomy</li></ul><p>Without APIs, modern software architecture — microservices, cloud systems, mobile apps — would not be possible.</p><h3>API Thinking vs Function Thinking</h3><blockquote><strong><em>API Thinking:</em></strong><em> “I need an endpoint to get users.”</em></blockquote><blockquote><strong><em>Function Thinking:</em></strong><em> “What resource or capability am I exposing to other systems?”</em></blockquote><p>APIs are not just endpoints. They define system boundaries.</p><h3>Key Takeaway</h3><p><strong>APIs exist to enable communication between independently evolving systems over a network through stable, standardized contracts.</strong></p><p>If you internalize this, REST design stops feeling arbitrary and starts feeling inevitable.</p><h3>What Comes Next</h3><p>In the next article, we will go deeper:</p><p><strong>HTTP From Scratch — What Actually Travels Over the Network</strong></p><p>Because to truly understand APIs, you must understand the messages that carry them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe363656b387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Finished My First Book — and It Changed How I Prepare for Interviews]]></title>
            <link>https://medium.com/@tejassadashiva/i-finished-my-first-book-and-it-changed-how-i-prepare-for-interviews-670c33b31982?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/670c33b31982</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[career-advice]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 15:25:42 GMT</pubDate>
            <atom:updated>2026-02-16T15:30:47.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Finished My First Book — and It Changed How I Prepare for Interviews</h3><p>I had never finished a book in my life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKKgvZMOeHJrOGK9EQ25Vw.png" /><figcaption>Deep Work</figcaption></figure><p>Not because I didn’t buy them. I bought many. I started many. I abandoned all of them somewhere between excitement and overwhelm.</p><p>At some point, I accepted a quiet belief:</p><blockquote><em>“Maybe I’m just not someone who reads books.”</em></blockquote><p>At the same time, I was preparing for software engineering interviews. My days were filled with DSA practice, design concepts, random tutorials, and new tech exploration — yet I constantly felt behind.</p><p>Busy, but not progressing.</p><p>Then I picked up <em>Deep Work</em> by Cal Newport.</p><p>I didn’t expect it to be different.</p><p>But it was the first book I stayed with — day after day — until the end.</p><h3>The Real Problem Wasn’t Knowledge</h3><p>I thought I needed more topics, more resources, more hours.</p><p>What I actually needed was depth.</p><p>My preparation looked like this:</p><ul><li>Try a DSA problem</li><li>Get stuck</li><li>Switch to another topic</li><li>Watch videos</li><li>Check phone</li><li>Repeat</li></ul><p>I was working a lot, but building very little confidence.</p><p>The book described deep work as the ability to focus on cognitively demanding tasks without distraction.</p><p>That sentence hit me because interview preparation is exactly that.</p><p>You can’t solve algorithmic problems or design systems with fragmented attention.</p><h3>The Shift That Changed My Preparation</h3><p>Before this, I used schedules occasionally, but without meaning. I was scheduling tasks, not protecting focus.</p><p>After understanding deep work, I simplified everything.</p><p>Instead of trying to study everything, I focused on two things:</p><p><strong>DSA first. LLD second.</strong></p><p>And instead of planning topics, I planned depth.</p><h3>My DSA sessions became:</h3><ul><li>One hard problem</li><li>No switching for 60–90 minutes</li><li>Accept getting stuck</li><li>No checking solutions early</li></ul><p>It felt uncomfortable at first.</p><p>But it also felt real.</p><h3>The Hardest Enemy Was Self-Doubt</h3><p>The biggest distraction wasn’t social media.</p><p>It was the voice that said:</p><p>“Maybe you’re not good at this.”</p><p>Whenever a problem didn’t click quickly, I wanted to escape to something easier.</p><p>Deep work forced me to stay.</p><p>And staying taught me something important:</p><p>Understanding doesn’t come suddenly. It forms slowly while you sit with confusion.</p><h3>Why This Book Meant More Than Productivity</h3><p>By the time I reached the end, I realized the biggest change wasn’t in my schedule.</p><p>It was in my identity.</p><p>I proved to myself that I could stay with something difficult across days without quitting.</p><p>That feeling matters more than any technique.</p><p>Because interview preparation is long, uncertain, and mentally demanding.</p><p>Consistency matters more than bursts of motivation.</p><h3>What I’m Carrying Forward</h3><p>I don’t plan to optimize every minute of my life.</p><p>I’m just doing a few things differently:</p><ul><li>Scheduling deep work before everything else</li><li>Reducing the number of active goals</li><li>Protecting my attention</li><li>Ending the day cleanly</li></ul><p>Nothing dramatic. Just deliberate.</p><h3>If You’re Preparing for Interviews</h3><p>You probably don’t need more resources.</p><p>You probably need fewer distractions and more depth.</p><p>Deep work didn’t make preparation easier.</p><p>It made it calmer.</p><p>And for the first time, I don’t feel like I’m running in circles.</p><h3>Closing</h3><p>Finishing this book didn’t turn me into a productivity expert.</p><p>It just showed me that focus is trainable, depth is possible, and progress doesn’t require chaos.</p><p>It starts with staying.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=670c33b31982" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: Closing the Loop on Kadane: From Sums to Invariants]]></title>
            <link>https://medium.com/@tejassadashiva/part-3-closing-the-loop-on-kadane-from-sums-to-invariants-1e0fb20ed346?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e0fb20ed346</guid>
            <category><![CDATA[dsa-courses]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 14:08:28 GMT</pubDate>
            <atom:updated>2026-02-11T14:08:28.954Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is the conclusion of a series Kadane on sums where I stopped memorizing Kadane’s Algorithm and started understanding why it works.</blockquote><p>If you haven’t read the previous parts, start here:</p><ul><li><a href="https://medium.com/@tejassadashiva/i-didnt-understand-kadane-s-algorithm-until-i-stopped-memorizing-it-e94881bb4a86"><strong>Part 1</strong></a><strong>:</strong> <em>I Didn’t Understand Kadane’s Algo Until I Stopped Memorizing It</em></li><li><a href="https://medium.com/@tejassadashiva/part-2-why-i-needed-to-stop-memorizing-other-problems-too-f6b36ee207dd"><strong>Part 2</strong></a><strong>:</strong> <em>Why I Needed to Stop Memorizing Other Problems Too</em></li></ul><p>This final part is about <strong>closure</strong> — not another trick, not another variation, but a mental model you can reuse confidently.</p><h3>What Kadane Is Not</h3><p>Kadane is <strong>not</strong>:</p><ul><li>a clever one-pass trick</li><li>a magic formula</li><li>something you memorize as curr = max(x, curr + x)</li></ul><p>If that’s how you learned it, you will eventually:</p><ul><li>freeze while coding</li><li>fail variants</li><li>lose confidence under pressure</li></ul><p>I did.</p><h3>The Real Problem Kadane Solves</h3><p>Kadane answers a very specific brute-force question:</p><blockquote><em>Out of all subarrays, which one gives the best result?</em></blockquote><p>Brute force does this by:</p><ul><li>choosing every (l, r)</li><li>computing the sum</li><li>comparing all of them</li></ul><p>Kadane doesn’t change the goal. It changes <strong>how much useless work we do</strong>.</p><h3>The Turning Point: Dominance</h3><p>The key insight I was missing for years:</p><blockquote><em>Some subarrays are </em><strong><em>provably useless</em></strong><em> for all future answers.</em></blockquote><p>Consider two subarrays that:</p><ul><li>end at the same index i</li><li>have sums S1 and S2</li><li>where S1 &lt; S2</li></ul><p>No matter what elements come next:</p><ul><li>Both subarrays will receive the <strong>same future additions</strong></li><li>The smaller one will <strong>never overtake</strong> the larger one</li></ul><p>So we discard it.</p><p>This idea is called <strong>dominance</strong>.</p><p>Kadane is nothing more than <em>systematic dominance elimination</em>.</p><h3>The Only State That Survives</h3><p>Once dominance is clear, the state becomes obvious:</p><blockquote><em>At index </em><em>i, only the </em><strong><em>maximum-sum subarray ending at </em></strong><strong><em>i</em></strong><em> is worth keeping.</em></blockquote><p>Everything else ending at i is dominated.</p><p>This single sentence is the <strong>entire algorithm</strong>.</p><h3>The Invariant (This Is the Algorithm)</h3><p>An invariant is something that must <strong>always be true</strong>.</p><p>Kadane’s invariant:</p><blockquote><em>At every index </em><em>i, we maintain the maximum possible subarray sum ending exactly at </em><em>i.</em></blockquote><p>Because:</p><ul><li>It dominates all other subarrays ending at i</li><li>It is sufficient for all future extensions</li></ul><p>If this invariant holds, the code is correct.</p><p>If it breaks, the code is wrong — even if it passes samples.</p><h3>Why the Code Looks So Simple</h3><p>Once the invariant is fixed, the transition is mechanical:</p><p>At index i, with value x:</p><ul><li>Either start a new subarray at i</li><li>or extend the previous dominant subarray</li></ul><p>That’s it.</p><p>The famous line:</p><pre>curr = Math.max(x, curr + x);</pre><p>This is <strong>not a trick</strong>.<br>It’s a direct translation of the invariant.</p><h3>Why Variants Stop Being Scary</h3><p>Once I understood Kadane this way, variants stopped feeling random.</p><h3>One deletion</h3><ul><li>State splits into: <em>deleted</em> and <em>not deleted</em></li><li>Dominance still applies within each category</li></ul><h3>Length ≥ K</h3><ul><li>The right end is fixed</li><li>The left contribution becomes the variable</li><li>Dominance applies to <strong>excluded prefixes</strong></li></ul><h3>Circular array</h3><ul><li>Same dominance</li><li>Different traversal</li></ul><p>No new magic.<br>Same reasoning.</p><h3>Kadane Is a Thinking Pattern, Not a Formula</h3><p>Here is the mental checklist I now use:</p><ol><li>What is the brute-force candidate?</li><li>What work repeats?</li><li>Which states are dominated?</li><li>What minimal state survives?</li><li>What invariant must always hold?</li><li>Translate mechanically to code</li></ol><p>If a problem fits this checklist, it’s a Kadane-family.</p><h3>Curated practice list (Kadane on sums only)</h3><p>When practicing these problems, don’t start with code.<br> Start by answering:</p><ul><li>What is the brute-force candidate?</li><li>Which states are dominated?</li><li>What invariant must always hold?</li></ul><p>If you can answer those, the code will write itself.</p><h3>Level 1 — Core invariant</h3><p>These force the <em>ending-at-i</em> invariant.</p><ol><li><strong>LC 53 — Maximum Subarray</strong><br> <em>Goal:</em> Derive Kadane from brute force<br> <em>Focus:</em> Why dominated prefixes are discarded</li><li><strong>LC 1749 — Maximum Absolute Sum of Any Subarray</strong><br> <em>Goal:</em> See max &amp; min Kadane symmetry<br> <em>Focus:</em> Same invariant, flipped objective</li></ol><h3>Level 2 — State expansion</h3><p>These test whether dominance still holds when state splits.</p><ol><li><strong>LC 1186 — Maximum Subarray Sum with One Deletion</strong><br> <em>Goal:</em> Learn state partitioning<br> <em>Focus:</em> Dominance within each category</li><li><strong>LC 152 — Maximum Product Subarray</strong><br> <em>Goal:</em> Understand why multiple states survive<br> <em>Focus:</em> Why sign flips prevent naïve dominance</li></ol><h3>Level 3 — Constraint injection</h3><p>These test whether you can <em>adapt</em> the invariant.</p><ol><li><strong>LC 1191 — K-Concatenation Maximum Sum</strong><br> <em>Goal:</em> Extend Kadane beyond one pass<br> <em>Focus:</em> When dominance applies globally vs locally</li><li><strong>LC 918 — Maximum Sum Circular Subarray</strong><br> <em>Goal:</em> Recognize when to reframe the array<br> <em>Focus:</em> Same invariant, different traversal</li></ol><blockquote>If you can solve the first three confidently, Kadane on sums is done.</blockquote><h3>Final Closure</h3><p>Kadane on sums is <strong>done</strong> when:</p><ul><li>You no longer memorize the formula</li><li>You can derive it from dominance</li><li>You can explain <em>why</em> a state is discarded</li><li>Code feels boring, not scary</li></ul><p>For me, this was the difference between:</p><blockquote><em>“I’ve solved Kadane before”</em></blockquote><p>and</p><blockquote><em>“I trust myself to solve Kadane variants.”</em></blockquote><p>That confidence is the real algorithm.</p><h3>What Comes Next</h3><p>Kadane doesn’t stop at sums.<br>The same dominance idea appears in:</p><ul><li>prefix-state problems</li><li>balanced subarrays</li><li>monotonic queues</li></ul><p>But that’s the next phase.</p><p>This article closes the chapter on <strong>Kadane&#39;s over sums</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e0fb20ed346" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Why I Needed to Stop Memorizing Other Problems Too]]></title>
            <link>https://medium.com/@tejassadashiva/part-2-why-i-needed-to-stop-memorizing-other-problems-too-f6b36ee207dd?source=rss-1b52eb892356------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6b36ee207dd</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Tejas S]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 11:29:56 GMT</pubDate>
            <atom:updated>2026-02-09T11:29:56.701Z</atom:updated>
            <content:encoded><![CDATA[<p><em>(This continues directly from part1: </em><a href="https://medium.com/@tejassadashiva/i-didnt-understand-kadane-s-algorithm-until-i-stopped-memorizing-it-e94881bb4a86"><em>Kadane’s article</em></a><em>)</em></p><p>If Kadane taught me one thing, it’s this:</p><blockquote><strong><em>Knowing the answer without knowing the </em>reason<em> feels like cheating the brain.</em></strong></blockquote><p>When I solved Kadane <em>before</em>, I did it by pattern recognition:</p><ul><li>“Oh, this is Kadane.”</li><li>“Use prefix sums.”</li><li>“Apply sliding window.”</li></ul><p>Great — <em>until the next problem doesn’t look like Kadane.</em></p><p>Every time I saw a problem that <em>resembled</em> Kadane, I copied the pattern in and hoped it would stick. Sometimes it did. Often it didn’t.</p><p>That’s when I realized something subtle:</p><blockquote><strong><em>I wasn’t memorizing solutions — I was memorizing excuses to not understand.</em></strong></blockquote><p>And that realization changed everything.</p><h3>The Missing Layer Was Not More Patterns — It Was Reasoning Itself</h3><p>Most DSA resources teach like this:</p><ol><li>Pattern</li><li>Template</li><li>Code</li><li>Testcases</li></ol><p>This works only if the <em>pattern</em> matches the <em>problem name</em>.</p><p>But real DSA questions — especially in interviews and contests — are <em>often new, unseen, or slightly twisted versions.</em></p><p>What I needed was not more solved problems,<br><strong>but a way to <em>think</em> about problems so that I can solve them even when they look unfamiliar.</strong></p><p>That’s when my approach shifted:</p><h3>The Thinking Loop That Changed Everything</h3><p>Instead of asking:</p><blockquote><em>“Which pattern is this?”</em></blockquote><p>I started asking:</p><blockquote><em>“What is being </em>repeated<em> in brute force?”</em></blockquote><p>Then:</p><blockquote><em>“What can I </em>throw away<em> safely?”</em></blockquote><p>And then:</p><blockquote><em>“What information must </em>survive<em>?”</em></blockquote><p>This loop became my mental training sequence:</p><pre>Brute force → Pain → Dominance → State → Invariant</pre><p>Let’s break this down in human language.</p><h3>Step 1 — Brute Force (Not as Scary as It Sounds)</h3><p>For any problem, before thinking of optimization:</p><blockquote><em>Try to describe a correct but slow solution — just in words, not code.</em></blockquote><p>This forces you to <em>feel</em> the structure of the problem.</p><p>For example:</p><ul><li>Kadane on subarrays? Enumerate all subarrays.</li><li>Max Product? Enumerate all products.</li><li>Stock problem? Enumerate all buy–sell pairs.</li></ul><p>That sounds tedious — that’s why it’s useful.</p><p>The <em>tension</em> from that tedium is how intuition begins.</p><h3>Step 2 — Pain (The Real Teacher)</h3><p>Brute force always hurts computationally.</p><p>From that pain, invariably, one truth emerges:</p><blockquote><em>“Something gets recalculated unnecessarily.”</em></blockquote><p>And that’s the exact question your intuition must ask:</p><blockquote><em>“What knowledge is being thrown away and why is that wasteful?”</em></blockquote><p>This is fundamentally different from pattern recognition.<br>It is an <strong>analysis of repetition</strong> — the core of all algorithms.</p><h3>Step 3 — Dominance (The Real Insight)</h3><p>This is the game-changer.</p><p>Ask:</p><blockquote><em>“If one piece of information is worse than another in every possible future scenario, can I </em>discard<em> it?”</em></blockquote><p>This simple but profound idea is what separates:</p><ul><li>copying known answers from</li><li>reasoning about new problems</li></ul><p>In Kadane, a smaller sum up to a point is always worse than a larger sum going to that point.<br>In stock problems, a higher buy price is always worse than a lower one for future profits.</p><p>In both cases, we discard inferior options not because of a pattern but because they can <em>never</em> win in any future scenario.</p><p>That’s dominance.</p><h3>Step 4 — State (What Survives)</h3><p>Once you identify what you can throw away, what remains is the <em>state</em> — the information that still <em>matters</em>.</p><p>In Kadane:</p><ul><li>The best sum ending at a point matters.</li></ul><p>In Stock Buy–Sell:</p><ul><li>The minimum buy price matters.</li></ul><p>This is not a magic formula — it’s a conclusion drawn from the earlier steps.</p><h3>Step 5 — Invariant (What Must Always Be True)</h3><p>Finally, we state the invariant — a truth that must remain valid no matter how far we move forward in the problem.</p><p>In Kadane, the invariant is:</p><blockquote><em>“At any index, the stored sum is the best possible ending precisely at that point.”</em></blockquote><p>This is the <em>reason</em> the algorithm works — not the pattern.</p><h3>Why This Way Works Better</h3><p>When I first did Kadane, I <em>knew the answer</em>, but I couldn’t explain the <em>reason</em>, so my brain treated it like a trick.<br>Now I <em>understand the reasoning</em>, meaning the next time I see a twist, my brain <em>feels the shape of the problem</em>, not the name of the pattern.</p><p>This is true mastery of intuition — not memorization.</p><h3>What I Learned From Other Problems</h3><p>After perfecting Kadane, I tried other subarray questions:</p><ul><li>Maximum product subarray</li><li>Subarray with optional deletion</li><li>Maximum subarray with constraints</li><li>Longest subarray with unique elements</li></ul><p>And the same sequence worked.</p><p>What changes is the <strong>type of dominance</strong>, but the <em>concept still applies</em>.</p><p>This is why the brute-force → pain → dominance → state → invariant structure is not a pattern checklist — it’s a <em>thinking system</em>.</p><h3>A Few Lessons I Now Use Every Time</h3><p>Instead of asking:</p><blockquote><em>“Which pattern is this?”</em></blockquote><p>I now ask:</p><ol><li>What is the correct brute-force idea (even if slow)?</li><li>What repeated work hurts performance?</li><li>What past information can never help the future?</li><li>What information must survive?</li><li>What invariant must hold to make the final answer correct?</li></ol><p>This is not just for Kadane-style problems — this applies everywhere, from <strong>trees</strong> to <strong>graphs</strong>, <strong>DP</strong> to <strong>greedy</strong> sequences.</p><h3>What’s Next</h3><p>Understanding Kadane was just the beginning — the first foothold in a mountain.</p><p>But the <em>way up</em> — the real path to intuition — is through careful reasoning and invariant thinking.<br>Not through memorizing lists.<br>Not through random practice.</p><p>This is the way <em>real experts</em> build intuition.</p><h3>Closing Thought</h3><p>Most people solve problems like pattern recognition.<br>I solve them like a <em>reason reconstruction</em>.</p><p>And once you make that shift, you’ll find that even “hard problems” become approachable — not because they are easy, but because you have the right <em>way to think about them</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6b36ee207dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>