<?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 Girishlalwani on Medium]]></title>
        <description><![CDATA[Stories by Girishlalwani on Medium]]></description>
        <link>https://medium.com/@girishlalwani2010?source=rss-2f2df87f87cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c2ilOKRtF_IpYG7Y71Ex0w.jpeg</url>
            <title>Stories by Girishlalwani on Medium</title>
            <link>https://medium.com/@girishlalwani2010?source=rss-2f2df87f87cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:02:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@girishlalwani2010/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[Trie/Segment Tree Pattern Questions]]></title>
            <link>https://medium.com/@girishlalwani2010/trie-segment-tree-pattern-questions-529686a35150?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/529686a35150</guid>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 19:37:16 GMT</pubDate>
            <atom:updated>2026-11-10T12:12:48.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trie Data Structure: From Basic Prefix Search to Advanced Patterns — A Problem-Driven Approach</h3><h3>Introduction</h3><p>When preparing for Data Structures and Algorithms interviews, learning a data structure in isolation is rarely enough.</p><p>A better approach is to start with a basic problem, understand why a particular data structure works, and then gradually explore how the same structure can solve more advanced variations.</p><p>That’s the approach I followed while studying Tries.</p><p>We started with basic insertion, search, and prefix matching. Then we explored wildcard searches, dictionary-based replacement, autocomplete, backtracking, prefix validation, and finally prefix aggregates.</p><p>Interestingly, the last problem, <strong>Map Sum Pairs (LeetCode 677)</strong>, introduced an idea that led us beyond Tries and toward Fenwick Trees and Segment Trees.</p><p>This article captures that progression.</p><h3>1. Understanding the Trie: Insert, Search, and Prefix</h3><h3>Problem 1: Implement Trie (LeetCode 208)</h3><p>The first question is straightforward:</p><p>How do we efficiently store words and search for them?</p><p>Consider inserting these words:</p><ul><li>apple</li><li>app</li><li>bat</li><li>ball</li></ul><p>A Trie stores words character by character, sharing common prefixes.</p><h3>Visual representation</h3><pre>root<br>                /    \<br>               a      b<br>               |      |<br>               p      a<br>               |      |<br>               p      t*<br>              / \     |<br>             l   *    l<br>             |        |<br>             e*       l*</pre><p>* represents the end of a complete word.</p><p>Notice something important:</p><p>The word app is a complete word, but it is also a prefix of apple.</p><p>Therefore, reaching a Trie node does not necessarily mean we have found a complete word.</p><p>We need a separate isEnd flag.</p><h3>Java implementation</h3><pre>class TrieNode {<br>    TrieNode[] children = new TrieNode[26];<br>    boolean isEnd;<br>}</pre><pre>class Trie {<br>    TrieNode root;</pre><pre>    public Trie() {<br>        root = new TrieNode();<br>    }</pre><pre>    public void insert(String word) {<br>        TrieNode node = root;</pre><pre>        for (char ch : word.toCharArray()) {<br>            int index = ch - &#39;a&#39;;</pre><pre>            if (node.children[index] == null) {<br>                node.children[index] = new TrieNode();<br>            }</pre><pre>            node = node.children[index];<br>        }</pre><pre>        node.isEnd = true;<br>    }</pre><pre>    public boolean search(String word) {<br>        TrieNode node = findNode(word);<br>        return node != null &amp;&amp; node.isEnd;<br>    }</pre><pre>    public boolean startsWith(String prefix) {<br>        return findNode(prefix) != null;<br>    }</pre><pre>    private TrieNode findNode(String word) {<br>        TrieNode node = root;</pre><pre>        for (char ch : word.toCharArray()) {<br>            int index = ch - &#39;a&#39;;</pre><pre>            if (node.children[index] == null) {<br>                return null;<br>            }</pre><pre>            node = node.children[index];<br>        }</pre><pre>        return node;<br>    }<br>}</pre><h3>What did we learn?</h3><p>There are three fundamental operations:</p><p>OperationMeaningComplexityInsertAdd a wordO(L)SearchCheck whether a complete word existsO(L)StartsWithCheck whether a prefix existsO(P)</p><p>Here, L is the word length and P is the prefix length.</p><p><strong>Pattern identified:</strong></p><p>Whenever a problem involves repeated prefix searches across a collection of strings, a Trie is a natural candidate.</p><h3>2. Wildcard Search: Trie + Branching DFS</h3><h3>Problem 2: Design Add and Search Words Data Structure (LeetCode 211)</h3><p>The next problem introduces a small but important change.</p><p>Instead of searching for an exact word, we need to support a wildcard character ..</p><p>For example:</p><pre>Dictionary:<br>bad<br>dad<br>mad</pre><pre>Search:<br>pad  -&gt; false<br>bad  -&gt; true<br>.ad  -&gt; true<br>b..  -&gt; true</pre><p>The wildcard can represent any single character.</p><h3>Why does the basic Trie search fail?</h3><p>In the previous problem, every character gave us exactly one path to follow.</p><p>For example:</p><pre>b -&gt; a -&gt; d</pre><p>But consider:</p><pre>.ad</pre><p>At the first character, we don’t know which child to choose.</p><p>We must explore all available children.</p><p>This changes our traversal from a simple iterative search to DFS.</p><h3>Visual intuition</h3><pre>root<br>           /  |  \<br>          b   d   m<br>          |   |   |<br>          a   a   a<br>          |   |   |<br>          d*  d*  d*</pre><p>For .ad, we explore:</p><pre>root<br>        /   |   \<br>       b    d    m<br>       |    |    |<br>       a    a    a<br>       |    |    |<br>       d    d    d</pre><p>If any path reaches a valid word ending, return true.</p><h3>Java implementation</h3><pre>public boolean search(String word) {<br>    return dfs(root, word, 0);<br>}</pre><pre>private boolean dfs(TrieNode node, String word, int index) {</pre><pre>    if (index == word.length()) {<br>        return node.isEnd;<br>    }</pre><pre>    char ch = word.charAt(index);</pre><pre>    if (ch == &#39;.&#39;) {<br>        for (TrieNode child : node.children) {<br>            if (child != null &amp;&amp;<br>                dfs(child, word, index + 1)) {<br>                return true;<br>            }<br>        }</pre><pre>        return false;<br>    }</pre><pre>    int pos = ch - &#39;a&#39;;</pre><pre>    if (node.children[pos] == null) {<br>        return false;<br>    }</pre><pre>    return dfs(node.children[pos], word, index + 1);<br>}</pre><h3>What changed conceptually?</h3><p>In LC 208:</p><pre>One character -&gt; One path</pre><p>In LC 211:</p><pre>Normal character -&gt; One path<br>Wildcard character -&gt; Multiple possible paths</pre><p>This is the important transition.</p><p><strong>Pattern identified:</strong></p><p>When a Trie search contains wildcard characters, branching conditions, or multiple possible next characters, combine Trie traversal with DFS/backtracking.</p><p>The worst-case search can explore many branches, depending on the number of wildcard characters.</p><h3>3. Prefix Matching: Replace Words</h3><h3>Problem 3: Replace Words (LeetCode 648)</h3><p>Now let’s consider a different problem.</p><p>We are given a dictionary of root words and a sentence.</p><p>We need to replace each word with its shortest matching root.</p><p>Example:</p><pre>Dictionary:<br>cat<br>bat<br>rat</pre><pre>Sentence:<br>the cattle was rattled by the battery</pre><pre>Output:<br>the cat was rat by the bat</pre><h3>Why is a Trie useful here?</h3><p>We need to find the shortest prefix of every sentence word that exists in the dictionary.</p><p>Consider:</p><pre>cattle<br> |<br> c -&gt; a -&gt; t<br>           |<br>           l -&gt; e</pre><p>As soon as we reach cat, we encounter an isEnd = true node.</p><p>We can stop immediately.</p><p>There is no need to traverse the remaining characters.</p><h3>Core algorithm</h3><ol><li>Insert all dictionary roots into the Trie.</li><li>For each sentence word, start from the root.</li><li>Traverse character by character.</li><li>If a terminal node is reached, return the prefix.</li><li>If the path ends without reaching a terminal node, return the original word.</li></ol><h3>Java traversal</h3><pre>private String findRoot(String word) {<br>    TrieNode node = root;<br>    StringBuilder prefix = new StringBuilder();</pre><pre>    for (char ch : word.toCharArray()) {<br>        int index = ch - &#39;a&#39;;</pre><pre>        if (node.children[index] == null) {<br>            return word;<br>        }</pre><pre>        node = node.children[index];<br>        prefix.append(ch);</pre><pre>        if (node.isEnd) {<br>            return prefix.toString();<br>        }<br>    }</pre><pre>    return word;<br>}</pre><h3>What did we learn?</h3><p>In LC 208, we searched for a complete word.</p><p>In LC 648, we stop at the first terminal node because we need the shortest valid prefix.</p><p><strong>Pattern identified:</strong></p><p>Trie + early termination at the first valid prefix.</p><p>This is useful for dictionary matching, word replacement, and prefix-based filtering.</p><h3>4. Autocomplete: Search Suggestions System</h3><h3>Problem 4: Search Suggestions System (LeetCode 1268)</h3><p>Now let’s extend prefix matching.</p><p>Instead of returning just one matching prefix, we need to return up to three lexicographically smallest products for every prefix of the search word.</p><p>Example:</p><pre>Products:<br>mobile<br>mouse<br>moneypot<br>monitor<br>mousepad</pre><pre>Search word:<br>mouse</pre><p>Expected suggestions:</p><pre>m       -&gt; mobile, moneypot, monitor</pre><pre>mo      -&gt; mobile, moneypot, monitor</pre><pre>mou     -&gt; mouse, mousepad</pre><pre>mous    -&gt; mouse, mousepad</pre><pre>mouse   -&gt; mouse, mousepad</pre><h3>What is new?</h3><p>Previously, we only needed to know whether a prefix existed.</p><p>Now we need to retrieve information associated with that prefix.</p><p>One possible Trie design is to store suggestions at every node.</p><pre>root<br> |<br> m  -&gt; [mobile, moneypot, monitor]<br> |<br> o  -&gt; [mobile, moneypot, monitor]<br> |<br> u  -&gt; [mouse, mousepad]<br> |<br> s  -&gt; [mouse, mousepad]<br> |<br> e  -&gt; [mouse, mousepad]</pre><p>If the products are sorted lexicographically before insertion, we can maintain only the first three products at each node.</p><h3>Core algorithm</h3><ol><li>Sort the products.</li><li>Insert each product into the Trie.</li><li>At each node, store up to three matching products.</li><li>Traverse the search word one character at a time.</li><li>Return the suggestions stored at each prefix node.</li></ol><h3>What did we learn?</h3><p>A Trie node does not have to store only children and an isEnd flag.</p><p>It can also store useful information associated with the prefix represented by that node.</p><p><strong>Pattern identified:</strong></p><p>Trie + prefix-specific metadata.</p><p>This is the foundation of autocomplete and search suggestion systems.</p><h3>5. Trie + Backtracking: Word Search II</h3><h3>Problem 5: Word Search II (LeetCode 212)</h3><p>This is a more advanced problem because it combines two techniques:</p><ul><li>Trie</li><li>DFS/backtracking on a grid</li></ul><p>We are given a character board and a list of words.</p><p>We need to find all dictionary words that can be constructed by moving horizontally or vertically through adjacent cells.</p><p>Example:</p><pre>Board:</pre><pre>o a a n<br>e t a e<br>i h k r<br>i f l v</pre><pre>Words:<br>oath<br>pea<br>eat<br>rain</pre><pre>Output:<br>oath<br>eat</pre><h3>Why not search each word independently?</h3><p>Suppose we have 1,000 dictionary words.</p><p>If we run a separate grid DFS for every word, we repeatedly explore the same prefixes.</p><p>This is where Trie becomes useful.</p><h3>The combined approach</h3><p>First, insert all dictionary words into a Trie.</p><p>Then start DFS from each board cell.</p><p>At every step:</p><ol><li>Check whether the current character exists in the Trie.</li><li>If not, stop exploring that path.</li><li>If the current Trie node represents a complete word, add it to the result.</li><li>Explore the four neighbouring cells.</li><li>Backtrack by marking the current board cell as visited.</li></ol><h3>Visual intuition</h3><p>Suppose the current board path is:</p><pre>o -&gt; a -&gt; t -&gt; h</pre><p>We follow the same path in the Trie:</p><pre>root<br> |<br> o<br> |<br> a<br> |<br> t<br> |<br> h*</pre><p>If a character is not present in the current Trie node, we immediately prune that DFS branch.</p><p>This is the major optimization.</p><h3>Important optimization: pruning</h3><p>After finding a word, we can remove its terminal marker to avoid reporting duplicates.</p><p>We can also remove dead Trie branches after they no longer contain any remaining words.</p><h3>What did we learn?</h3><p>This problem is not just a Trie problem.</p><p>It is a combination of:</p><pre>Trie + Grid DFS + Backtracking + Pruning</pre><p><strong>Pattern identified:</strong></p><p>When multiple words must be searched inside a grid, a Trie can share common prefixes and reduce repeated exploration.</p><h3>6. Prefix Validation and Traversal</h3><h3>Problem 6: Longest Word in Dictionary (LeetCode 720)</h3><p>Now let’s look at a different variation.</p><p>We need to find the longest word such that every prefix of that word is also present in the dictionary.</p><p>Example:</p><pre>Words:<br>w<br>wo<br>wor<br>worl<br>world<br>banana</pre><pre>Output:<br>world</pre><p>Why is world valid?</p><p>Because all its prefixes exist:</p><pre>w<br>wo<br>wor<br>worl<br>world</pre><h3>What is the important observation?</h3><p>We are not simply looking for the longest word.</p><p>We are looking for the longest word whose every intermediate prefix is a valid word.</p><p>This changes how we traverse the Trie.</p><p>A node is eligible for traversal only if its parent represents a complete word.</p><h3>Visual intuition</h3><pre>root<br> |<br> w* <br> |<br> o*<br> |<br> r*<br> |<br> l*<br> |<br> d*</pre><p>Every node along the path must be terminal.</p><p>If a prefix is missing, we cannot extend that path.</p><h3>Java approach</h3><p>One approach is to sort the words and build the Trie.</p><p>Another elegant approach is to use a Trie with BFS/DFS, allowing traversal only through terminal nodes.</p><h3>What did we learn?</h3><p>The isEnd flag is useful for more than checking whether a complete word exists.</p><p>It can control whether we are allowed to continue exploring deeper nodes.</p><p><strong>Pattern identified:</strong></p><p>Trie traversal + prefix validation.</p><p>This pattern is useful when every intermediate prefix must satisfy a condition.</p><h3>7. Prefix Aggregates: Map Sum Pairs</h3><h3>Problem 7: Map Sum Pairs (LeetCode 677)</h3><p>This problem introduces a new dimension.</p><p>Until now, we mostly stored structural information:</p><ul><li>Children</li><li>Word-ending flags</li><li>Suggestions</li><li>Dictionary words</li></ul><p>Now we need to store numerical information at each Trie node.</p><p>The problem asks us to support:</p><pre>insert(key, value)<br>sum(prefix)</pre><p>The sum operation returns the total values of all keys starting with the given prefix.</p><p>Example:</p><pre>insert(&quot;apple&quot;, 3)</pre><pre>sum(&quot;ap&quot;) -&gt; 3</pre><pre>insert(&quot;app&quot;, 2)</pre><pre>sum(&quot;ap&quot;) -&gt; 5</pre><h3>Why does a Trie work?</h3><p>Consider:</p><pre>apple = 3<br>app   = 2</pre><p>Both keys share the prefix:</p><pre>a -&gt; p -&gt; p</pre><p>Instead of searching all stored keys whenever we receive sum(&quot;app&quot;), we can maintain the sum directly at the corresponding Trie node.</p><h3>The important insight: Store an aggregate at each node</h3><p>Each node stores:</p><pre>int sum;</pre><p>During insertion, we update the sum of every node along the key’s path.</p><p>But there is a problem.</p><p>What happens if an existing key is updated?</p><p>For example:</p><pre>insert(&quot;apple&quot;, 3)<br>insert(&quot;apple&quot;, 5)</pre><p>If we simply add 5 to every node, we incorrectly count the old value again.</p><p>We need to account for the previous value.</p><h3>The delta technique</h3><p>Calculate:</p><pre>int oldValue = values.getOrDefault(key, 0);</pre><pre>int delta = newValue - oldValue;</pre><p>Then propagate only the difference:</p><pre>node.sum += delta;</pre><p>For example:</p><pre>Initial value:<br>apple = 3</pre><pre>Updated value:<br>apple = 8</pre><pre>delta = 8 - 3 = 5</pre><p>Instead of adding 8 again, we add only 5 to the nodes along the apple path.</p><h3>Java implementation</h3><pre>class MapSum {</pre><pre>    class TrieNode {<br>        TrieNode[] children = new TrieNode[26];<br>        int sum;<br>    }</pre><pre>    private TrieNode root;<br>    private Map&lt;String, Integer&gt; values;</pre><pre>    public MapSum() {<br>        root = new TrieNode();<br>        values = new HashMap&lt;&gt;();<br>    }</pre><pre>    public void insert(String key, int val) {</pre><pre>        int oldValue = values.getOrDefault(key, 0);<br>        int delta = val - oldValue;</pre><pre>        values.put(key, val);</pre><pre>        TrieNode node = root;</pre><pre>        for (char ch : key.toCharArray()) {</pre><pre>            int index = ch - &#39;a&#39;;</pre><pre>            if (node.children[index] == null) {<br>                node.children[index] = new TrieNode();<br>            }</pre><pre>            node = node.children[index];</pre><pre>            node.sum += delta;<br>        }<br>    }</pre><pre>    public int sum(String prefix) {</pre><pre>        TrieNode node = root;</pre><pre>        for (char ch : prefix.toCharArray()) {</pre><pre>            int index = ch - &#39;a&#39;;</pre><pre>            if (node.children[index] == null) {<br>                return 0;<br>            }</pre><pre>            node = node.children[index];<br>        }</pre><pre>        return node.sum;<br>    }<br>}</pre><h3>Complexity</h3><p>Let L be the key length and P be the prefix length.</p><p>OperationComplexityInsert/updateO(L)Prefix sumO(P)SpaceO(total characters + stored keys)</p><h3>What did we learn?</h3><p>This is an important conceptual transition.</p><p>A Trie node can maintain an aggregate over all keys passing through that node.</p><p>The aggregate does not have to be just a boolean or a list.</p><p>It can be:</p><ul><li>Sum</li><li>Count</li><li>Minimum</li><li>Maximum</li><li>Other prefix-specific information</li></ul><p>The important idea is to maintain useful information at the node so that queries can be answered without traversing the entire subtree.</p><h3>8. The Bigger Pattern: From Trie to Fenwick Tree and Segment Tree</h3><p>This was the most interesting connection from the sequence of problems.</p><p>In Map Sum Pairs, we used:</p><pre>delta = newValue - oldValue;</pre><p>Then we propagated that delta along every Trie node belonging to the key.</p><p>Why?</p><p>Because every node on that path represents a prefix aggregate that includes the key’s value.</p><p>Now consider a completely different problem.</p><p>Suppose we have an array:</p><pre>nums = [1, 3, 5, 7]</pre><p>We need to support:</p><ol><li>Updating an element.</li><li>Calculating the sum of an arbitrary range.</li></ol><p>This is LeetCode 307 — Range Sum Query: Mutable.</p><p>If we update index 1 from 3 to 10:</p><pre>delta = 10 - 3 = 7</pre><p>The total sum changes by 7.</p><p>Instead of recomputing the entire sum, we propagate the delta to the relevant stored aggregates.</p><p>This is the same underlying idea we used in Map Sum Pairs.</p><h3>8.1 Connection to Fenwick Tree</h3><p>A Fenwick Tree stores partial prefix sums in a compact array.</p><p>When an element changes, we calculate:</p><pre>delta = newValue - oldValue;</pre><p>Then update the Fenwick Tree nodes that cover that index.</p><p>The operations are:</p><pre>// Point update<br>while (i &lt;= n) {<br>    bit[i] += delta;<br>    i += i &amp; -i;<br>}</pre><pre>// Prefix sum<br>while (i &gt; 0) {<br>    sum += bit[i];<br>    i -= i &amp; -i;<br>}</pre><p>Both operations take O(log N).</p><h3>8.2 Connection to Segment Tree</h3><p>A Segment Tree also stores aggregates, but each node represents an interval.</p><p>For example:</p><pre>[0,3] = 16<br>                 /         \<br>          [0,1] = 4       [2,3] = 12<br>           /    \          /    \<br>          1      3        5      7</pre><p>If index 1 changes from 3 to 10:</p><pre>delta = 10 - 3 = 7</pre><p>We update the leaf and every ancestor on its path to the root.</p><p>The root becomes:</p><pre>16 + 7 = 23</pre><p>The same delta principle works.</p><p>However, Segment Trees are more flexible because their merge operation can represent sums, minimums, maximums, GCD, XOR, and more.</p><h4><strong>Range Sum Query Mutable (Leetcode 307)</strong></h4><h3>Fenwick Tree vs Segment Tree</h3><p>FeatureFenwick TreeSegment TreePoint updateO(log N)O(log N)Prefix sumO(log N)O(log N)Range sumO(log N)O(log N)Range minimumLimitedSupportedLazy propagationSpecialized techniquesNatural fitImplementationSimplerMore flexible</p><p>The important lesson is that the delta technique is not exclusive to Tries.</p><p>It is a general technique for maintaining aggregates when underlying values change.</p><h3>9. Complete Learning Progression</h3><p>Let’s summarize the journey.</p><p>ProblemLeetCodePattern learnedImplement Trie208Insert, search, prefixDesign Add and Search Words211Wildcard + branching DFSReplace Words648Prefix matching + early terminationSearch Suggestions System1268Prefix metadata + top-KWord Search II212Trie + grid DFS + pruningLongest Word in Dictionary720Prefix validation + traversalMap Sum Pairs677Prefix aggregates + delta updates</p><p>These seven problems cover several important Trie patterns.</p><p>They are not intended to represent every possible Trie problem. Instead, they provide a structured foundation for recognizing how the data structure evolves as problem requirements become more sophisticated.</p><h3>10. How to Recognize the Pattern in Interviews</h3><p>When you encounter a string or dictionary-based problem, ask yourself these questions:</p><p><strong>Question 1: Do multiple words share common prefixes?</strong></p><p>Consider a Trie.</p><p><strong>Question 2: Do I need exact word searches and prefix searches?</strong></p><p>Start with the basic Trie pattern.</p><p><strong>Question 3: Can a character represent multiple possible choices?</strong></p><p>Consider Trie + DFS/backtracking.</p><p><strong>Question 4: Do I need the shortest matching prefix?</strong></p><p>Consider terminal-node detection and early termination.</p><p><strong>Question 5: Do I need to return suggestions or metadata associated with a prefix?</strong></p><p>Store additional information at Trie nodes.</p><p><strong>Question 6: Must every intermediate prefix satisfy a condition?</strong></p><p>Use terminal flags to control traversal.</p><p><strong>Question 7: Do I need to maintain an aggregate for all keys sharing a prefix?</strong></p><p>Consider storing aggregates at Trie nodes. If existing values can change, consider delta updates.</p><h3>Conclusion: The Real Learning</h3><p>The biggest takeaway from these problems is not the Trie implementation itself.</p><p>It is understanding how the information stored at each node changes depending on the query requirements.</p><p>We started with:</p><pre>TrieNode:<br>    children<br>    isEnd</pre><p>Then gradually extended the node:</p><pre>TrieNode:<br>    children<br>    isEnd<br>    suggestions<br>    aggregate</pre><p>The data structure remained fundamentally the same. What changed was the information we maintained and how we traversed it.</p><p>Finally, Map Sum Pairs introduced us to a broader idea:</p><p><strong>Maintain aggregates incrementally using delta updates instead of recomputing everything.</strong></p><p>That idea connects Tries to Fenwick Trees and Segment Trees.</p><p>This is how I prefer to study DSA: not as a collection of unrelated LeetCode solutions, but as a sequence of problems that build reusable patterns and intuition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xD3JF0tvjPi6sTBk9iX-lw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=529686a35150" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[News Feed System Design.]]></title>
            <link>https://medium.com/@girishlalwani2010/news-feed-system-design-7d2afc8f80ad?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d2afc8f80ad</guid>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 19:27:11 GMT</pubDate>
            <atom:updated>2026-11-01T19:27:11.905Z</atom:updated>
            <content:encoded><![CDATA[<h3>News Feed System Design — Staff Engineer Interview Revision Notes</h3><h3>1. Problem and requirements</h3><p>Design a scalable news feed system where users can:</p><ul><li>Create posts containing text, images, or videos.</li><li>Follow and unfollow other users.</li><li>View a personalized news feed.</li><li>Retrieve feed entries using pagination.</li></ul><h3>Non-functional requirements</h3><p>RequirementTarget / assumptionRegistered users500 millionDaily active users (DAU)100 millionDaily posts20 millionPost creation latencyP99 &lt; 500 msFeed retrieval latencyP99 &lt; 500 msFeed propagation99% within 60 secondsFeed consistencyEventual consistency</p><p>Important distinction: post creation should be durable before returning success, while feed propagation can happen asynchronously.</p><p>Availability and consistency should be specified separately for each operation rather than treated as a single trade-off.</p><h3>2. Capacity estimation</h3><p>We’ll use the following assumptions:</p><p>ParameterAssumptionRegistered users500 millionDAU100 millionDAU as percentage of registered users20%DAU creating posts daily10%Daily active post creators10 millionPosts per creator per day2Feed API requests per DAU per day10Average post metadata size1 KBAverage eligible followers per write-fanout author200</p><p>These are illustrative interview assumptions, not actual measurements from a specific social network.</p><h3>A. Post creation throughput</h3><p>10% of 100 million DAU create posts:</p><p>[<br>100M \times 10% = 10M\ creators<br>]</p><p>Each creator publishes 2 posts per day:</p><p>[<br>10M \times 2 = 20M\ posts/day<br>]</p><p>Average write throughput:</p><p>[<br>\frac{20M}{86,400} \approx 231\ posts/sec<br>]</p><p>MetricValuePosts/day20 millionAverage write throughput231 posts/secPeak at 5× average1,157 posts/secPeak at 10× average2,315 posts/sec</p><p>For initial sizing, we’ll use a 10× write peak factor.</p><h3>B. Feed read throughput</h3><p>Assume each DAU makes 10 feed API requests per day.</p><p>[<br>100M \times 10 = 1B\ feed\ requests/day<br>]</p><p>Average read throughput:</p><p>[<br>\frac{1B}{86,400} \approx 11,574\ requests/sec<br>]</p><p>MetricValueFeed requests/day1 billionAverage read throughput11.6K requests/secPeak at 5× average57.9K requests/sec</p><p>Note: These are feed API requests, not necessarily feed sessions. A user scrolling through multiple pages can generate several requests in one session.</p><h3>C. Post metadata storage</h3><p>Assume 1 KB of metadata per post.</p><p>[<br>20M \times 1KB = 20GB/day<br>]</p><p>PeriodRaw metadata storageDaily20 GBMonthly (30 days)600 GBYearly7.3 TB10 years73 TB</p><p>This excludes indexes, database overhead, replication, backups, logs, and feed data.</p><p>For example, three copies of the yearly raw metadata would represent approximately 21.9 TB of storage before additional database overhead.</p><p>Images and videos should be stored separately in object storage such as S3. Their storage capacity cannot be calculated without assumptions about the percentage of posts containing media and the average media size.</p><h3>D. Fanout amplification</h3><p>Assume an average of 200 eligible followers for authors whose posts use fanout-on-write.</p><p>Average post creation rate:</p><p>[<br>231\ posts/sec<br>]</p><p>Average feed insertions:</p><p>[<br>231 \times 200 = 46,200\ feed\ insertions/sec<br>]</p><p>At a 10× write peak:</p><p>[<br>2,315 \times 200 = 463,000\ feed\ insertions/sec<br>]</p><p>MetricValueAverage post creation231/secAverage eligible followers200Average feed insertions46.2K/secPeak feed insertions (10×)463K/sec</p><p>These calculations apply to the fanout-on-write population. High-follower celebrities are excluded because we use fanout-on-read for them.</p><p><strong>Key insight:</strong> Even though we create only around 231 posts/sec on average, those posts can generate approximately 46K feed insertions/sec.</p><p>This is the main reason we need asynchronous fanout workers, Kafka, Redis, and a hybrid fanout strategy.</p><h3>3. Post creation architecture</h3><p>Recommended flow:</p><ol><li>Client requests a pre-signed media upload URL.</li><li>Post Service generates the URL.</li><li>Client uploads media directly to S3.</li><li>Client calls Post Service to create the post.</li><li>Post Service validates the uploaded object, ownership, size, and upload completion.</li><li>Post metadata is persisted in Post DB.</li><li>A PostCreated event is recorded in an outbox in the same database transaction.</li><li>Outbox publisher publishes the event to Kafka.</li></ol><h3>Why direct S3 upload?</h3><ul><li>Application servers don’t have to handle large media payloads.</li><li>Reduces application-server bandwidth and processing.</li><li><strong>Media processing can happen asynchronously.</strong></li></ul><p>Keep media processing separate from post creation. A video may need transcoding, thumbnail generation, or moderation.</p><h3>Why transactional outbox?</h3><p>Post DB and Kafka are separate systems. A direct database write followed by Kafka publication can fail between the two operations.</p><p>The transactional outbox ensures the post and the intent to publish its event are committed together.</p><h3>4. Core database model</h3><h3>Posts</h3><p>Important fields:</p><ul><li>post_id</li><li>author_id</li><li>text_content</li><li>visibility</li><li>status</li><li>created_at</li><li>updated_at</li></ul><p>Useful access path:</p><p>(author_id, created_at)</p><p>Media metadata can be stored separately, with a reference to the post and its S3 object key.</p><h3>Follows</h3><p>Recommended relationship:</p><p>follower_id, followee_id, created_at</p><p>Primary key:</p><p>(follower_id, followee_id)</p><p>Additional index:</p><p>(followee_id, follower_id)</p><p>Why two indexes?</p><ol><li>Find users whom a given user follows.</li><li>Find followers of a given user.</li></ol><p>The second access pattern is important during fanout.</p><p>Celebrity classification should be maintained separately rather than treated as a permanent property of a follow relationship.</p><h3>5. Fanout: the most important architectural decision</h3><p>There are two basic approaches.</p><h3>A. Fanout-on-write</h3><p>When User A creates a post:</p><ol><li>Persist the post.</li><li>Publish PostCreated.</li><li>Fetch User A’s followers.</li><li>Insert the new post ID into each follower’s feed.</li></ol><p>Advantages:</p><ul><li>Very fast feed reads.</li><li>Expensive work happens asynchronously.</li><li>Good for normal users with manageable follower counts.</li></ul><p>Disadvantage:</p><ul><li>Write amplification.</li><li>A celebrity with millions of followers can generate millions of feed updates for one post.</li></ul><h3>B. Fanout-on-read</h3><p>Instead of inserting a celebrity’s post into every follower’s Redis feed:</p><ol><li>Store the post normally.</li><li>Do not fan it out to every follower.</li><li>When a follower requests their feed, retrieve recent posts from the celebrity accounts they follow.</li><li>Merge these posts with precomputed feed candidates.</li></ol><p>Advantage: avoids enormous fanout writes.</p><p>Disadvantage: increases feed-read computation.</p><h3>C. Hybrid fanout — recommended</h3><p>User categoryStrategyNormal usersFanout-on-writeHigh-follower / celebrity usersFanout-on-readInactive usersAvoid continuously materializing their feeds</p><p>This is a more practical architecture than choosing fanout-on-write or fanout-on-read for everyone.</p><p>Classification should be based on follower count and operational cost, not an arbitrary permanent user flag.</p><h3>6. Redis feed design</h3><p>Recommended logical structure:</p><p>feed:{userId} → ZSET</p><p>Each sorted-set entry:</p><ul><li>Member: postId</li><li>Score: createdAt timestamp</li></ul><p>Example:</p><pre>ZADD feed:U101 1793521000000 P1001<br>ZADD feed:U101 1793521100000 P1002</pre><p>Retrieve the latest posts:</p><pre>ZREVRANGE feed:U101 0 19</pre><h3>Why Sorted Set?</h3><ul><li>Maintains ordering by timestamp.</li><li>Supports efficient retrieval of recent entries.</li><li>Supports pagination.</li><li>ZADD with the same member is idempotent for repeated inserts.</li></ul><h3>Redis memory and key cardinality</h3><p>We discussed two alternatives:</p><p><strong>One ZSET per user</strong></p><p>Good for:</p><ul><li>Independent feed retrieval.</li><li>Independent expiry and trimming.</li><li>Natural Redis Cluster distribution across keys.</li></ul><p>Bad when:</p><ul><li>Materializing feeds for all 500 million registered users.</li><li>Storing too many entries per feed.</li></ul><p><strong>One ZSET for every 1,000 users</strong></p><p>Although this reduces the number of keys, it creates:</p><ul><li>Hot-key risks.</li><li>Large individual sorted sets.</li><li>More complicated user-specific range queries.</li><li>Difficult per-user TTL and eviction.</li><li>More operational complexity.</li></ul><p><strong>Decision:</strong> Prefer one ZSET per active user, not one ZSET for every registered user.</p><p>Keep a bounded number of recent entries, for example 500 as an initial design assumption. Use activity-based cache policies and avoid materializing feeds for inactive users.</p><p>Remember: reducing Redis key count does not automatically reduce total memory consumption. Total feed entries and per-key traffic matter more.</p><p>Redis Cluster distributes different keys across nodes, but an individual large ZSET belongs to one hash slot and is not automatically distributed across multiple primary nodes.</p><h3>7. Kafka architecture — two-stage fanout pipeline</h3><p>Instead of having one consumer process an entire follower list, separate event coordination from actual feed updates.</p><h3>Stage 1: Post-created events</h3><p>Topic:</p><p>social.post-created</p><p>Kafka key:</p><p>postId</p><p>Example:</p><pre>{<br>  &quot;eventId&quot;: &quot;EVT-1001&quot;,<br>  &quot;eventType&quot;: &quot;POST_CREATED&quot;,<br>  &quot;postId&quot;: &quot;P1001&quot;,<br>  &quot;authorId&quot;: &quot;U101&quot;,<br>  &quot;createdAtEpochMillis&quot;: 1793521000000,<br>  &quot;visibility&quot;: &quot;PUBLIC&quot;<br>}</pre><p>Why postId?</p><ul><li>Distributes independent posts across partitions.</li><li>Avoids concentrating all posts from one celebrity into one partition.</li><li>Does not guarantee author-level ordering.</li></ul><p>Kafka guarantees ordering within a partition, not across partitions.</p><h3>Stage 2: Fanout Coordinator</h3><p>Consumer group:</p><p>fanout-coordinators</p><p>The coordinator:</p><ol><li>Consumes POST_CREATED.</li><li>Retrieves followers from Follow DB.</li><li>Uses keyset pagination rather than loading millions of followers into memory.</li><li>Divides followers into manageable chunks.</li><li>Publishes fanout tasks to a separate Kafka topic.</li></ol><p>Example SQL:</p><pre>SELECT follower_id<br>FROM follows<br>WHERE followee_id = :authorId<br>  AND follower_id &gt; :lastFollowerId<br>ORDER BY follower_id<br>LIMIT 500;</pre><h3>Stage 3: Fanout tasks</h3><p>Topic:</p><p>social.feed-fanout-tasks</p><p>Kafka key:</p><p>chunkId</p><p>Example:</p><pre>{<br>  &quot;eventType&quot;: &quot;FANOUT_CHUNK&quot;,<br>  &quot;chunkId&quot;: &quot;P1001-CHUNK-001&quot;,<br>  &quot;postId&quot;: &quot;P1001&quot;,<br>  &quot;authorId&quot;: &quot;U101&quot;,<br>  &quot;recipientIds&quot;: [<br>    &quot;U000001&quot;,<br>    &quot;U000002&quot;,<br>    &quot;U000003&quot;<br>  ],<br>  &quot;createdAtEpochMillis&quot;: 1793521000000<br>}</pre><p>Why chunkId?</p><p>Chunks belonging to the same post should be independently distributable across Kafka partitions.</p><p>This lets multiple workers process different portions of the same follower list concurrently.</p><p>An alternative is to put a follower cursor in the task and let workers fetch recipients themselves. Explicit recipient IDs make tasks self-contained and easier to retry, while cursors can reduce Kafka message size if pagination is snapshot-safe and retryable.</p><h3>Stage 4: Fanout workers</h3><p>Consumer group:</p><p>feed-fanout-workers</p><p>Each worker:</p><ol><li>Consumes a fanout chunk.</li><li>Iterates through its recipients.</li><li>Updates their Redis feeds.</li><li>Commits the Kafka offset after successful processing.</li></ol><p>Example:</p><pre>ZADD feed:U000001 1793521000000 P1001<br>ZADD feed:U000002 1793521000000 P1001<br>ZADD feed:U000003 1793521000000 P1001</pre><p>Use Redis pipelining or batches to reduce network round trips.</p><h3>Why two topics?</h3><p>TopicKeyResponsibilitysocial.post-createdpostIdDistribute post eventssocial.feed-fanout-taskschunkIdDistribute follower updates</p><p>This separates post-level event processing from recipient-level work distribution.</p><h3>8. Scaling the fanout process</h3><p>Consider a celebrity with 10 million followers and a chunk size of 500.</p><p>If we used fanout-on-write:</p><p>[<br>\frac{10M}{500} = 20,000 \text{ fanout tasks}<br>]</p><p>However, our recommended hybrid architecture would normally avoid generating these 20,000 tasks for a celebrity. It would use fanout-on-read instead.</p><p>For normal fanout-on-write authors, the number of chunks per post is:</p><p>[<br>\text{Chunks per post} =<br>\left\lceil \frac{\text{Follower count}}{500} \right\rceil<br>]</p><p>With an assumed 200 followers per normal author, most posts would fit into one chunk.</p><p>The coordinator should not load all followers into memory.</p><p>For more advanced scaling, introduce:</p><ul><li>Durable fanout job records.</li><li>Multiple chunk planners.</li><li>Chunk level processing or in general, consumer</li><li>Independently retryable chunks.</li><li>Chunk-level progress tracking.</li><li>A separate fanout completion state.</li></ul><p>For very high-follower accounts, fanout-on-read can avoid this workload altogether.</p><h3>9. Failure handling and idempotency</h3><p>The system should assume at-least-once delivery, not exactly-once business execution.</p><p>FailureExpected handlingPost Service crashes after DB commitOutbox publisher retriesCoordinator crashes before publishing tasksKafka replays uncommitted post eventCoordinator crashes after publishing some tasksPost event may replay; duplicate chunks must be safeWorker crashes during Redis updatesKafka replays uncommitted chunkWorker updates Redis but crashes before offset commitChunk may replay; repeated ZADD is safe</p><p>Use stable IDs such as:</p><ul><li>eventId</li><li>chunkId</li><li>postId</li></ul><p>For duplicate processing:</p><ul><li>Deterministic chunk IDs help identify duplicate tasks.</li><li>ZADD with the same post ID prevents duplicate members in a recipient feed.</li><li>External business side effects require their own idempotency mechanism.</li></ul><p>An outbox or durable task table can protect the coordinator’s output. Publishing to Kafka and committing the source offset are separate operations unless using an appropriate transactional consume-process-produce design.</p><p><strong>Important:</strong> Kafka consumer groups provide partition reassignment and replay. They do not automatically guarantee that an external side effect executes exactly once.</p><h3>10. Feed read architecture</h3><p>When a user opens their feed:</p><ol><li>Feed Service retrieves post IDs from Redis.</li><li>It batch-fetches post details from Post Cache or Post DB.</li><li>It fetches author details as needed.</li><li>It applies visibility and access-control checks.</li><li>It fetches recent celebrity posts separately.</li><li>It merges candidates.</li><li>It applies ranking if required.</li><li>It returns a paginated response.</li></ol><p>Avoid the N+1 query problem: retrieve post details in batches, not one database request per post.</p><h3>Pagination</h3><p>Start with 20–50 posts per page, with an upper limit such as 100.</p><p>Use cursor pagination rather than offset pagination.</p><p>For chronological ordering, the cursor can represent:</p><p>(created_at, post_id)</p><p>The post ID provides a deterministic tie-breaker for posts with the same timestamp.</p><h3>11. Additional design concerns</h3><h3>Follow / Unfollow</h3><ul><li>Follow: decide whether to backfill recent posts.</li><li>Unfollow: stop future fanout and ensure old cached entries are no longer visible.</li><li>Block: filter blocked users’ posts.</li><li>Private account: verify that the viewer is authorized.</li></ul><h3>Post deletion</h3><p>A deleted post ID may still be in Redis. Feed Service must check deletion/visibility state or use a reliable invalidation strategy.</p><h3>Ranking</h3><p>Start with chronological ordering:</p><p>created_at DESC, post_id DESC</p><p>Later, add a ranking stage after candidate generation and visibility filtering.</p><h3>Cache misses and Redis failure</h3><p>Redis is a serving layer, not the only durable source of feed information. The system needs a fallback or reconstruction strategy using durable post and follow data.</p><h3>12. Final architecture summary</h3><pre>500M Registered Users<br>100M DAU<br>20M Posts/Day<br>       |<br>       v<br>Client / API Gateway<br>       |<br>       +-----------------------+<br>       |                       |<br>  Post Service             Feed Service<br>       |                       |<br>  Post DB + Outbox       Redis Feed Cache<br>       |                       |<br>  Outbox Publisher       Celebrity post lookup<br>       |<br>  Kafka: social.post-created<br>       |<br>  Fanout Coordinator Group<br>       |<br>  Follow DB (paginated follower lookup)<br>       |<br>  Kafka: social.feed-fanout-tasks<br>       |<br>  Fanout Worker Group<br>       |<br>  Redis: feed:{userId}<br>       |<br>  Feed Service hydrates and returns posts</pre><h3>13. Key interview takeaways</h3><ol><li><strong>Fanout is the central scalability challenge.</strong> One post can create hundreds or thousands of downstream feed updates.</li><li><strong>Hybrid fanout is the practical choice.</strong> Fanout-on-write for normal users and fanout-on-read for celebrities.</li><li><strong>Separate the two stages.</strong> Post event coordination and recipient feed updates should scale independently.</li><li><strong>Partition by the right entity.</strong> postId distributes independent post events; chunkId distributes fanout work.</li><li><strong>Redis is a serving cache.</strong> Use bounded per-active-user sorted sets rather than materializing every registered user’s feed.</li><li><strong>Design for at-least-once delivery.</strong> Use stable IDs and idempotent operations.</li><li><strong>Outbox solves the DB-to-Kafka dual-write problem.</strong></li><li><strong>Read-path hydration should be batched.</strong> Avoid N+1 queries.</li><li><strong>Privacy and deletion checks are mandatory.</strong> Cached feed IDs can become stale.</li><li><strong>Don’t add complexity without a requirement.</strong> Start with chronological feeds, then introduce ranking and more sophisticated fanout planning as needed.</li></ol><h3>14. Areas to explore further</h3><p>These areas were identified but not fully designed in our discussion:</p><ul><li>Follow graph sharding and efficient follower pagination at large scale.</li><li>Distributed fanout planning for celebrity accounts.</li><li>Redis memory sizing and cluster capacity calculations.</li><li>Post DB sharding and cross-shard queries.</li><li>Feed reconstruction for users returning after long inactivity.</li><li>Ranking algorithms and candidate generation.</li><li>Backfill consistency during follow/unfollow operations.</li></ul><p><strong>Interview positioning:</strong> Be ready to explain not just the boxes in the architecture, but why each component exists, what its scaling bottleneck is, how it fails, and how the system recovers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d2afc8f80ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebCrawler System Design]]></title>
            <link>https://medium.com/@girishlalwani2010/webcrawler-system-design-360fa0e21d20?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/360fa0e21d20</guid>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 04:55:59 GMT</pubDate>
            <atom:updated>2026-10-12T04:59:41.633Z</atom:updated>
            <content:encoded><![CDATA[<p>Consolidated notes from the two design snapshots and our discussion: requirements, capacity, crawler/parser responsibilities, queues, storage, deduplication, Bloom filters, database partitioning/sharding, video handling, Kafka vs SQS, politeness, fault tolerance, and Staff-level interview questions.</p><p><strong>1. Problem Definition</strong></p><ul><li>Design a web crawler that extracts text data from the web and stores it to train an LLM.</li><li>The crawler can run for only 5 days.</li><li>Start from seed URLs and discover additional URLs while crawling.</li></ul><p><strong>2. Functional Requirements</strong></p><ul><li>Crawl the full web starting from seed URLs.</li><li>Fetch pages and extract useful text.</li><li>Extract links from fetched pages and feed them back into the frontier.</li><li>Store fetched/raw content and extracted text.</li><li>Track URL state so the same URL is not unnecessarily crawled again.</li></ul><p><strong>3. Non-Functional Requirements</strong></p><ul><li>Fault tolerant.</li><li>Polite: respect robots.txt and enforce per-domain rate/concurrency limits.</li><li>Scale to about 10B pages.</li><li>Complete within the 5-day window.</li></ul><p><strong>4. Capacity Estimation</strong></p><p><strong>Item</strong></p><p><strong>Estimate</strong></p><p>Pages</p><p>10B</p><p>Average page size</p><p>2 MB</p><p>Raw content</p><p>≈20 PB</p><p>5 days</p><p>432,000 seconds</p><p>Minimum average fetch rate</p><p>≈23,150 pages/sec</p><p>Average payload bandwidth</p><p>≈46.3 GB/sec ≈370 Gbps</p><p>Provisioning</p><p>Add headroom for retries, failures, uneven latency and protocol overhead</p><p>Staff-level framing: the 5-day deadline drives worker parallelism, aggregate network bandwidth, queue capacity, and backpressure.</p><p><strong>5. Original Design Snapshots</strong></p><p><strong>Snapshot 1 </strong>— requirements, core entities, interface and basic data flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*VtJXubJaozJPHECQBNtPCw.png" /></figure><p><strong>Snapshot 2</strong> — HLD, storage/queues, retries, Redis, DynamoDB and parsing workers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pX3J9lB2xUGuSxQ0Q9o29Q.png" /></figure><p><strong>6. Core Entities</strong></p><p><strong>Entity</strong></p><p><strong>Purpose</strong></p><p>URL metadata</p><p>Canonical URL, state/status, object-storage pointer, timestamps, retry count, content hash.</p><p>Domain metadata</p><p>robots.txt/policy information and domain-level crawl scheduling/rate state.</p><p>Raw content</p><p>Downloaded HTML/document in object storage.</p><p>Extracted text</p><p>Clean text used by downstream LLM-data processing.</p><p>Frontier item</p><p>URL eligible/scheduled for crawling.</p><p><strong>7. Interface</strong></p><ul><li>Input: set of seed URLs.</li><li>Output: extracted/stored text data.</li><li>Internal interfaces are queue-based: frontier queue for crawl work and parsing queue for downloaded content.</li></ul><p><strong>8. Recommended HLD</strong></p><p>Seed URLs<br> ↓<br> URL Frontier / Queue<br> ↓<br> Crawler Workers<br> ├── DNS / HTTP fetch<br> ├── robots.txt / domain politeness<br> ├── URL-state / deduplication<br> └── raw content → Object Storage<br> ↓<br> Parsing Queue<br> ↓<br> Parser Workers<br> ├── text → Text Storage / LLM pipeline<br> └── URLs → dedupe → Frontier</p><p>Clean separation: crawler workers fetch; parser workers parse HTML and extract text/links. The frontier decides what to crawl next. The metadata store records what we know about a URL. Object storage holds large content.</p><p><strong>9. Parser Should Not Poll the Database</strong></p><p>Use a durable parsing queue rather than making parser workers poll the metadata database.</p><p>Crawler → Parsing Queue → Parser Workers<br> Parser slower than crawler → queue depth rises → autoscale parsers</p><ul><li>Buffering and backpressure.</li><li>Independent scaling.</li><li>Retries/DLQ.</li><li>Database remains state storage, not a work queue.</li></ul><p><strong>10. Kafka Before Parser?</strong></p><p><strong>Choice</strong></p><p><strong>Use when</strong></p><p>SQS / durable work queue</p><p>One task should be processed by one parser worker; simple distribution, retries and DLQ.</p><p>Kafka</p><p>Multiple independent consumer groups need the same stream, replay, partitioned ordering, or stream processing.</p><p>Do not introduce Kafka merely because the system is large. Start with the simplest queue that satisfies the required semantics.</p><p><strong>11. URL Deduplication</strong></p><p>Discovered URL<br> ↓<br> Normalize URL<br> ↓<br> Fast Bloom-filter check<br> ↓<br> Authoritative conditional write<br> ↓<br> Frontier queue</p><ul><li>Normalize host casing, default ports, fragments and policy-defined canonicalization.</li><li>Bloom filter is an optimization, not the source of truth.</li><li>Use an atomic/conditional insert so two workers discovering the same URL cannot both win.</li><li>The authoritative store tracks URL state.</li></ul><p><strong>12. Bloom Filter: Where and Why?</strong></p><ul><li>Local in-memory Bloom filters are attractive because they avoid a network hop.</li><li>A shared RedisBloom filter is possible, but creates network traffic and a shared service that can become hot.</li><li>Bloom filters have false positives, so they cannot be authoritative.</li><li>For 10B elements at ~1% false-positive probability, the theoretical bit array is about 12 GB; optimal hash count is about 7.</li><li>If URL ownership is partitioned, local Bloom filters become more practical because each worker sees a bounded subset.</li></ul><p>RedisBloom concept:<br> BF.RESERVE visited_urls 0.01 10000000<br> BF.ADD visited_urls &lt;url&gt;<br> BF.EXISTS visited_urls &lt;url&gt;<br> <br> Use BF.EXISTS/BF.ADD as the fast probabilistic layer;<br> keep the metadata store as the correctness layer.</p><p><strong>13. Storage</strong></p><p><strong>Store</strong></p><p><strong>Data</strong></p><p><strong>Reason</strong></p><p>Object storage / S3</p><p>Raw HTML and large content; ≈20 PB at stated assumptions</p><p>Durable, scalable object storage.</p><p>SQL or distributed KV metadata store</p><p>URL state and small crawl metadata</p><p>Exact lookup, conditional insert, status updates.</p><p>Queue</p><p>URLs and parser tasks</p><p>Work distribution, retries, buffering.</p><p>Optional Redis</p><p>Temporary fast state / Bloom filter / rate limiting</p><p>Optimization, not authoritative URL state.</p><p><strong>14. Do We Really Need DynamoDB?</strong></p><p>No. A relational database can implement the metadata store. The choice should follow access pattern and operational requirements.</p><ul><li>Our primary operations are key-oriented: exact URL lookup, conditional insert, and status update.</li><li>A distributed key-value store is operationally convenient for this pattern.</li><li>SQL is attractive if relational queries, SQL tooling, or stronger relational transactions matter.</li><li>At 10B rows, do not assume one DB instance is enough; throughput, indexes, maintenance and replication matter.</li></ul><p><strong>15. Does 5 TB Require PostgreSQL Sharding?</strong></p><p>Not merely because it is 5 TB. PostgreSQL can handle multi-terabyte databases. The harder question is whether the cluster can sustain the required ingestion/state-update workload reliably.</p><ul><li>Start with partitioning and benchmark realistic reads/writes/indexes/maintenance.</li><li>If one PostgreSQL cluster cannot meet throughput or operational requirements, introduce horizontal sharding.</li><li>10B rows itself creates major operational concerns: indexes, vacuum/autovacuum, bloat, backups, replication and maintenance.</li></ul><p><strong>16. Sharding Key</strong></p><p>shard = hash(normalized_url) % N</p><ul><li>Good distribution across shards.</li><li>Direct routing for exact URL operations.</li><li>Avoids concentrating all URLs from one large domain onto one shard.</li><li>Domain-based sharding helps domain queries but risks hot shards for very large domains.</li><li>If domain queries become important, consider a separate access path/index rather than changing the primary key.</li></ul><p><strong>17. PostgreSQL / MySQL Sharding Options</strong></p><p><strong>Technology</strong></p><p><strong>Relevant approach</strong></p><p>PostgreSQL</p><p>Built-in table partitioning; distributed sharding via application-level sharding or technologies such as Citus.</p><p>MySQL</p><p>Built-in table partitioning; distributed sharding via application-level routing or technologies such as Vitess.</p><p>Partitioning ≠ sharding. Partitioning splits a table logically; sharding distributes data across independent database servers/clusters.</p><p><strong>18. Video Content</strong></p><p>Do not download/process video by default for this problem. The stated requirement is text extraction for LLM training.</p><p>HTML<br> ↓<br> Parser<br> ├── HTML/text → text pipeline<br> ├── PDF → document parser<br> ├── image → OCR/image pipeline<br> └── video URL → optional media pipeline</p><ul><li>A 2 MB average page does not mean every referenced resource is 2 MB.</li><li>A page can reference a huge video; blindly downloading it would break bandwidth assumptions.</li><li>If video transcription becomes a requirement, use a separate media pipeline: object storage → audio extraction → speech-to-text → optional OCR/frame analysis → text.</li></ul><p><strong>19. Politeness</strong></p><p>URL Frontier<br> ↓<br> domain-aware scheduling<br> ↓<br> per-domain rate/concurrency limit<br> ↓<br> crawler workers</p><ul><li>Fetch/cache robots.txt according to policy.</li><li>Respect applicable disallow rules and crawl-delay/politeness rules.</li><li>Maintain per-domain rate/concurrency state.</li><li>Use timeouts, exponential backoff, retry limits and temporary suppression for failing domains.</li><li>Achieve global throughput through concurrency across many domains, not by overloading one domain.</li></ul><p><strong>20. Fault Tolerance</strong></p><p><strong>Failure</strong></p><p><strong>Handling</strong></p><p>HTTP transient failure</p><p>Retry with exponential backoff + jitter.</p><p>Repeated failure</p><p>Retry limit → DLQ / failed state.</p><p>Parser failure</p><p>Queue retry; poison messages eventually go to DLQ.</p><p>Crawler crash</p><p>Queue visibility timeout / redelivery.</p><p>Metadata DB failure</p><p>Retry/backoff; Bloom filter does not replace authoritative state.</p><p>Object-storage failure</p><p>Retry; mark fetch complete only after durable persistence.</p><p>Slow domain</p><p>Per-domain backoff/concurrency reduction.</p><p><strong>21. Backpressure and Autoscaling</strong></p><p>Crawler rate &gt; Parser rate<br> ↓<br> Parsing queue depth ↑<br> ↓<br> Scale parser workers</p><ul><li>Use queue depth/age as scaling signals.</li><li>CPU alone is insufficient; crawler bottlenecks may be network or target-site latency.</li><li>Monitor progress against the required 23K+ pages/sec target.</li></ul><p><strong>22. Refined Staff-Level HLD</strong></p><p>Seed URLs<br> |<br> v<br> + — — — — — — — — — -+<br> | URL Frontier/SQS |<br> | priority + retry |<br> + — — — — -+ — — — — -+<br> |<br> v<br> + — — — — — — — — — — — -+<br> | Distributed Crawlers |<br> | DNS/HTTP/robots |<br> | domain rate limiting |<br> + — — + — — — — — — -+ — — +<br> | |<br> raw HTML | | discovered URLs<br> v |<br> + — — — — — -+ |<br> | Object | |<br> | Storage | |<br> + — — -+ — — -+ |<br> | |<br> v |<br> + — — — — — — -+ |<br> | Parse Queue | |<br> + — — — + — — — + |<br> | |<br> v |<br> + — — — — — — -+ |<br> | Parse Fleet | — — — + — → normalize/dedupe<br> + — — — + — — — + |<br> | v<br> v Metadata DB<br> Extracted Text<br> |<br> v<br> LLM Data Pipeline</p><p><strong>23. Key Decisions</strong></p><p><strong>Topic</strong></p><p><strong>Recommendation</strong></p><p>Frontier</p><p>Durable queue + domain-aware scheduler.</p><p>Raw content</p><p>Object storage.</p><p>Parser work</p><p>Queue-driven workers.</p><p>Kafka</p><p>Optional; justify it with multiple consumers/replay/stream semantics.</p><p>Dedup</p><p>Bloom optimization + authoritative conditional write.</p><p>Bloom</p><p>Prefer local RAM unless shared semantics justify RedisBloom.</p><p>Metadata DB</p><p>DynamoDB-like KV or partitioned/sharded SQL, based on access pattern.</p><p>Shard key</p><p>hash(normalized_url) for exact-URL workloads.</p><p>Video</p><p>Do not download by default; separate media pipeline.</p><p>Politeness</p><p>Per-domain scheduling/rate limiting + robots.txt.</p><p><strong>24. Staff Engineer Deep-Dive Questions</strong></p><ol><li>How do you guarantee 10B pages can be processed in 5 days?</li><li>What is the minimum page fetch rate and aggregate bandwidth?</li><li>How does the frontier select the next URL?</li><li>How do you enforce robots.txt and per-domain politeness?</li><li>How do you prevent duplicate crawling when many workers discover the same URL?</li><li>Why use a Bloom filter? What are false positives and how do they affect correctness?</li><li>Where would you store the Bloom filter and why?</li><li>Why is the metadata store authoritative rather than the Bloom filter?</li><li>Why object storage for raw HTML instead of the database?</li><li>Why not have parser workers poll the database?</li><li>When would Kafka be preferable to SQS?</li><li>What happens if parser throughput is lower than crawler throughput?</li><li>How do retries and DLQ work?</li><li>What happens when a domain becomes slow or unavailable?</li><li>Does 5 TB require database sharding? Why or why not?</li><li>Why hash(normalized_url) as the sharding key?</li><li>What happens to queries that need all URLs for a domain?</li><li>How do you reshard as the URL set grows?</li><li>What happens if object storage succeeds but the metadata update fails, or vice versa?</li><li>How would you extend the system to process video, PDF and image content?</li></ol><p><strong>25. One-Minute Interview Summary</strong></p><p>Use a distributed, queue-driven crawler. A domain-aware frontier schedules URLs; crawler workers fetch pages while enforcing DNS/HTTP timeouts, robots.txt and per-domain politeness. Raw content goes to object storage. Parser workers consume parsing tasks, extract text and links, and feed newly discovered URLs through normalization and authoritative deduplication before they return to the frontier. Metadata is separate from large content. The 5-day requirement means roughly 23K successful fetches/sec and ~46 GB/sec average payload bandwidth, so scale comes from horizontally scaled workers and massive cross-domain parallelism. Bloom filters reduce deduplication cost but are not the source of truth. SQL is viable; sharding is a throughput/operational decision rather than a consequence of 5 TB alone.</p><p><strong>Staff-level rule: </strong>Whenever introducing Kafka, Redis, DynamoDB, Citus, Vitess, or Bloom filters, first state the problem it solves and then the trade-off. Avoid choosing infrastructure simply because the system is large.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=360fa0e21d20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partition DP & Interval DP: 8 Problems That Build the Pattern]]></title>
            <link>https://medium.com/@girishlalwani2010/partition-dp-interval-dp-8-problems-that-build-the-pattern-05eceedbe672?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/05eceedbe672</guid>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 20:18:02 GMT</pubDate>
            <atom:updated>2026-10-07T20:18:02.750Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A pattern-first guide for Senior / Staff software engineering interviews</strong></p><p>The goal is not to memorize eight solutions. The goal is to recognize the recursion skeleton, define the smallest state, identify what the loop chooses, and know whether the answer is a MIN, MAX, or SUM.</p><p><em>This article focuses on recursive + memoized formulations because they make the decision structure visible. Once the recurrence is clear, bottom-up DP or optimization can be derived from it.</em></p><p><strong>The Two Engines</strong></p><p><strong>1. Partition DP: choose where the current segment ends</strong></p><p>dfs(start, constraint)<br> |<br> + — choose where current partition ends<br> |<br> + — calculate current segment contribution<br> |<br> + — solve the remaining suffix<br> |<br> + — MIN / MAX</p><p><strong>The important mental model: </strong>start tells us where the unprocessed suffix begins. The loop tries every legal endpoint for the current segment. The recursive call starts immediately after that endpoint.</p><p><strong>2. Interval / Split DP: choose the split point</strong></p><p>dfs(l, r)<br> |<br> + — choose split point k<br> |<br> + — solve left interval<br> |<br> + — solve right interval<br> |<br> + — add current contribution<br> |<br> + — MIN / MAX / SUM</p><p><strong>The important mental model: </strong>the state is an interval. The loop chooses a point inside that interval so the problem breaks into two independent subproblems.</p><p><strong>How to Recognize the Pattern in an Interview</strong></p><p>What is the smallest state that completely describes the remaining problem?</p><p>What does dfs(state) mean in one precise sentence?</p><p>What exactly does the loop choose: a segment end, a split point, the first operation, or the last operation?</p><p>What is the current segment/interval contribution?</p><p>How do I combine the children?</p><p>Am I taking MIN, MAX, or SUM across choices?</p><p>Can I maintain a running maximum or sum instead of rescanning?</p><p>Is any parameter just a temporary choice and therefore not part of the memoization state?</p><p><strong>The 8-Problem Map</strong></p><p><strong>1. Minimum Difficulty of a Job Schedule</strong></p><p><strong>LeetCode: </strong><a href="https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/">https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/</a></p><p><strong>State: </strong>(start, days)</p><p><strong>Recognition trigger: </strong>Jobs remain in order; choose where the current day ends.</p><p><strong>Recurrence: </strong>max(current segment) + best for remaining days</p><p><strong>Complexity: </strong>O(n² · d) time, O(n · d) space</p><p>This is the cleanest example of partition DP. At each state, try every legal endpoint for the current day. The loop stops early enough to leave at least one job for every remaining day.</p><p>class Solution {</p><p>public int minDifficulty(int[] jobs, int d) {</p><p>int n = jobs.length;</p><p>if (n &lt; d) {<br> return -1;<br> }</p><p>Integer[][] memo = new Integer[d + 1][n];</p><p>return dfs(jobs, d, 0, memo);<br> }</p><p>private int dfs(<br> int[] jobs,<br> int days,<br> int start,<br> Integer[][] memo) {</p><p>// Last day: all remaining jobs go here.<br> if (days == 1) {<br> int max = 0;</p><p>for (int i = start; i &lt; jobs.length; i++) {<br> max = Math.max(max, jobs[i]);<br> }</p><p>return max;<br> }</p><p>if (memo[days][start] != null) {<br> return memo[days][start];<br> }</p><p>int max = 0;<br> int answer = Integer.MAX_VALUE;</p><p>// Leave at least (days — 1) jobs.<br> for (int i = start; i &lt;= jobs.length — days; i++) {</p><p>max = Math.max(max, jobs[i]);</p><p>int rest = dfs(<br> jobs,<br> days — 1,<br> i + 1,<br> memo<br> );</p><p>answer = Math.min(<br> answer,<br> max + rest<br> );<br> }</p><p>return memo[days][start] = answer;<br> }<br>}</p><p><em>Mental shortcut: choose the end of today, keep the maximum of today, recurse on tomorrow, then take MIN.</em></p><p><strong>2. Split Array Largest Sum</strong></p><p><strong>LeetCode: </strong><a href="https://leetcode.com/problems/split-array-largest-sum/">https://leetcode.com/problems/split-array-largest-sum/</a></p><p><strong>State: </strong>(start, groups)</p><p><strong>Recognition trigger: </strong>Split an ordered array into a fixed number of contiguous groups and minimize the largest group sum.</p><p><strong>Recurrence: </strong>max(current group sum, best remaining value)</p><p><strong>Complexity: </strong>O(n² · k) time, O(n · k) space</p><p>class Solution {</p><p>public int splitArray(int[] nums, int k) {</p><p>int n = nums.length;<br> Integer[][] memo = new Integer[k + 1][n];</p><p>return dfs(nums, k, 0, memo);<br> }</p><p>private int dfs(<br> int[] nums,<br> int groups,<br> int start,<br> Integer[][] memo) {</p><p>if (groups == 1) {<br> int sum = 0;</p><p>for (int i = start; i &lt; nums.length; i++) {<br> sum += nums[i];<br> }</p><p>return sum;<br> }</p><p>if (memo[groups][start] != null) {<br> return memo[groups][start];<br> }</p><p>int currentSum = 0;<br> int answer = Integer.MAX_VALUE;</p><p>for (int i = start; i &lt;= nums.length — groups; i++) {</p><p>currentSum += nums[i];</p><p>int rest = dfs(<br> nums,<br> groups — 1,<br> i + 1,<br> memo<br> );</p><p>int candidate = Math.max(<br> currentSum,<br> rest<br> );</p><p>answer = Math.min(<br> answer,<br> candidate<br> );<br> }</p><p>return memo[groups][start] = answer;<br> }<br>}</p><p><em>Important: this problem also has a Binary Search on Answer solution. The DP formulation is still valuable because it shows the underlying partition decisions.</em></p><p><strong>3. Partition Array for Maximum Sum</strong></p><p><strong>LeetCode: </strong><a href="https://leetcode.com/problems/partition-array-for-maximum-sum/">https://leetcode.com/problems/partition-array-for-maximum-sum/</a></p><p><strong>State: </strong>start</p><p><strong>Recognition trigger: </strong>Choose the endpoint of the next partition; its length can be at most k.</p><p><strong>Recurrence: </strong>max(segment) × segment length + best suffix</p><p><strong>Complexity: </strong>O(n · k) time, O(n) space</p><p>class Solution {</p><p>public int maxSumAfterPartitioning(<br> int[] arr,<br> int k) {</p><p>Integer[] memo = new Integer[arr.length + 1];</p><p>return dfs(arr, k, 0, memo);<br> }</p><p>private int dfs(<br> int[] arr,<br> int k,<br> int start,<br> Integer[] memo) {</p><p>if (start == arr.length) {<br> return 0;<br> }</p><p>if (memo[start] != null) {<br> return memo[start];<br> }</p><p>int currentMax = 0;<br> int answer = Integer.MIN_VALUE;</p><p>for (int i = start;<br> i &lt; arr.length &amp;&amp; i &lt; start + k;<br> i++) {</p><p>currentMax = Math.max(<br> currentMax,<br> arr[i]<br> );</p><p>int length = i — start + 1;</p><p>int currentValue =<br> currentMax * length;</p><p>int rest = dfs(<br> arr,<br> k,<br> i + 1,<br> memo<br> );</p><p>answer = Math.max(<br> answer,<br> currentValue + rest<br> );<br> }</p><p>return memo[start] = answer;<br> }<br>}</p><p><strong>4. Palindrome Partitioning II</strong></p><p><strong>LeetCode: </strong><a href="https://leetcode.com/problems/palindrome-partitioning-ii/">https://leetcode.com/problems/palindrome-partitioning-ii/</a></p><p><strong>State: </strong>start</p><p><strong>Recognition trigger: </strong>Choose where the next palindromic piece ends.</p><p><strong>Recurrence: </strong>1 cut + best suffix (except when the palindrome reaches the end)</p><p><strong>Complexity: </strong>O(n²) time with palindrome precomputation, O(n²) space</p><p>class Solution {</p><p>public int minCut(String s) {</p><p>int n = s.length();</p><p>boolean[][] palindrome =<br> new boolean[n][n];</p><p>for (int i = n — 1; i &gt;= 0; i — ) {<br> for (int j = i; j &lt; n; j++) {</p><p>palindrome[i][j] =<br> s.charAt(i) == s.charAt(j)<br> &amp;&amp; (j — i &lt;= 1<br> || palindrome[i + 1][j — 1]);<br> }<br> }</p><p>Integer[] memo = new Integer[n];</p><p>return dfs(<br> s,<br> 0,<br> palindrome,<br> memo<br> );<br> }</p><p>private int dfs(<br> String s,<br> int start,<br> boolean[][] palindrome,<br> Integer[] memo) {</p><p>if (start == s.length()) {<br> return 0;<br> }</p><p>if (memo[start] != null) {<br> return memo[start];<br> }</p><p>int answer = Integer.MAX_VALUE;</p><p>for (int end = start;<br> end &lt; s.length();<br> end++) {</p><p>if (!palindrome[start][end]) {<br> continue;<br> }</p><p>int cuts =<br> (end == s.length() — 1)<br> ? 0<br> : 1 + dfs(<br> s,<br> end + 1,<br> palindrome,<br> memo<br> );</p><p>answer = Math.min(answer, cuts);<br> }</p><p>return memo[start] = answer;<br> }<br>}</p><p><strong>5. Matrix Chain Multiplication</strong></p><p><strong>State: </strong>(l, r)</p><p><strong>Recognition trigger: </strong>Choose where to split the matrix chain.</p><p><strong>Recurrence: </strong>left cost + right cost + cost of multiplying the two resulting matrices</p><p><strong>Complexity: </strong>O(m³) time, O(m²) space, where m is the number of matrices</p><p>class Solution {</p><p>static int matrixMultiplication(int[] arr) {</p><p>int n = arr.length — 1;</p><p>Integer[][] memo =<br> new Integer[n + 1][n + 1];</p><p>return dfs(arr, 1, n, memo);<br> }</p><p>private static int dfs(<br> int[] arr,<br> int l,<br> int r,<br> Integer[][] memo) {</p><p>// One matrix: no multiplication.<br> if (l == r) {<br> return 0;<br> }</p><p>if (memo[l][r] != null) {<br> return memo[l][r];<br> }</p><p>int answer = Integer.MAX_VALUE;</p><p>for (int k = l; k &lt; r; k++) {</p><p>int left = dfs(<br> arr,<br> l,<br> k,<br> memo<br> );</p><p>int right = dfs(<br> arr,<br> k + 1,<br> r,<br> memo<br> );</p><p>int currentCost =<br> arr[l — 1]<br> * arr[k]<br> * arr[r];</p><p>int total =<br> left + right + currentCost;</p><p>answer = Math.min(<br> answer,<br> total<br> );<br> }</p><p>return memo[l][r] = answer;<br> }<br>}</p><p><em>The split variable k is a choice, not part of the memoized state. The state is only the interval (l, r).</em></p><p><strong>6. Minimum Cost to Cut a Stick</strong></p><p><strong>LeetCode: </strong><a href="https://leetcode.com/problems/minimum-cost-to-cut-a-stick/">https://leetcode.com/problems/minimum-cost-to-cut-a-stick/</a></p><p><strong>State: </strong>(l, r)</p><p><strong>Recognition trigger: </strong>Choose the FIRST cut inside the current stick segment so the two sides become independent.</p><p><strong>Recurrence: </strong>current stick length + left interval cost + right interval cost</p><p><strong>Complexity: </strong>O(m³) time, O(m²) space</p><p>class Solution {</p><p>public int minCost(int n, int[] cuts) {</p><p>Arrays.sort(cuts);</p><p>int m = cuts.length;</p><p>int[] points =<br> new int[m + 2];</p><p>points[0] = 0;<br> points[m + 1] = n;</p><p>for (int i = 0; i &lt; m; i++) {<br> points[i + 1] = cuts[i];<br> }</p><p>Integer[][] memo =<br> new Integer[m + 2][m + 2];</p><p>return dfs(<br> points,<br> 0,<br> m + 1,<br> memo<br> );<br> }</p><p>private int dfs(<br> int[] points,<br> int l,<br> int r,<br> Integer[][] memo) {</p><p>if (r — l == 1) {<br> return 0;<br> }</p><p>if (memo[l][r] != null) {<br> return memo[l][r];<br> }</p><p>int answer = Integer.MAX_VALUE;</p><p>for (int c = l + 1; c &lt; r; c++) {</p><p>int currentCost =<br> points[r] — points[l];</p><p>int leftCost =<br> dfs(points, l, c, memo);</p><p>int rightCost =<br> dfs(points, c, r, memo);</p><p>int total =<br> currentCost<br> + leftCost<br> + rightCost;</p><p>answer = Math.min(<br> answer,<br> total<br> );<br> }</p><p>return memo[l][r] = answer;<br> }<br>}</p><p><em>Boundary insight: 0 and n are physical boundaries, not cuts. Adding them to the positional array makes the interval length simply points[r] — points[l].</em></p><p><strong>7. Burst Balloons</strong></p><p><strong>LeetCode: </strong><a href="https://leetcode.com/problems/burst-balloons/">https://leetcode.com/problems/burst-balloons/</a></p><p><strong>State: </strong>(l, r) over padded boundaries</p><p><strong>Recognition trigger: </strong>Choose the LAST balloon to burst in the interval.</p><p><strong>Recurrence: </strong>left subproblem + right subproblem + leftBoundary × balloon × rightBoundary</p><p><strong>Complexity: </strong>O(n³) time, O(n²) space</p><p>class Solution {</p><p>public int maxCoins(int[] nums) {</p><p>int n = nums.length;</p><p>int[] p = new int[n + 2];</p><p>p[0] = 1;<br> p[n + 1] = 1;</p><p>for (int i = 0; i &lt; n; i++) {<br> p[i + 1] = nums[i];<br> }</p><p>Integer[][] memo =<br> new Integer[n + 2][n + 2];</p><p>return dfs(p, 0, n + 1, memo);<br> }</p><p>private int dfs(<br> int[] p,<br> int l,<br> int r,<br> Integer[][] memo) {</p><p>if (l + 1 == r) {<br> return 0;<br> }</p><p>if (memo[l][r] != null) {<br> return memo[l][r];<br> }</p><p>int answer = 0;</p><p>// i is the LAST balloon to burst.<br> for (int i = l + 1; i &lt; r; i++) {</p><p>int left =<br> dfs(p, l, i, memo);</p><p>int right =<br> dfs(p, i, r, memo);</p><p>int current =<br> p[l] * p[i] * p[r];</p><p>int total =<br> left + right + current;</p><p>answer = Math.max(<br> answer,<br> total<br> );<br> }</p><p>return memo[l][r] = answer;<br> }<br>}</p><p><em>Why LAST? If i is the last balloon remaining in the interval, its neighbors are fixed at l and r. That makes its final contribution deterministic.</em></p><p><strong>8. Boolean Parenthesization</strong></p><p><strong>State: </strong>(l, r, wantTrue)</p><p><strong>Recognition trigger: </strong>Choose an operator split; count how many left/right truth combinations produce the requested result.</p><p><strong>Recurrence: </strong>SUM of valid combinations</p><p><strong>Complexity: </strong>O(n³) time, O(n²) states × 2 truth values</p><p>class Solution {</p><p>private static final int MOD = 1_000_000_007;</p><p>public int countWays(String expression) {</p><p>int n = expression.length();</p><p>Integer[][][] memo =<br> new Integer[n][n][2];</p><p>return dfs(<br> expression,<br> 0,<br> n — 1,<br> true,<br> memo<br> );<br> }</p><p>private int dfs(<br> String s,<br> int l,<br> int r,<br> boolean wantTrue,<br> Integer[][][] memo) {</p><p>if (l == r) {<br> boolean value =<br> s.charAt(l) == ‘T’;</p><p>return value == wantTrue ? 1 : 0;<br> }</p><p>int truth = wantTrue ? 1 : 0;</p><p>if (memo[l][r][truth] != null) {<br> return memo[l][r][truth];<br> }</p><p>long answer = 0;</p><p>for (int k = l + 1; k &lt; r; k += 2) {</p><p>long lt = dfs(s, l, k — 1, true, memo);<br> long lf = dfs(s, l, k — 1, false, memo);<br> long rt = dfs(s, k + 1, r, true, memo);<br> long rf = dfs(s, k + 1, r, false, memo);</p><p>long trueWays;</p><p>if (s.charAt(k) == ‘&amp;’) {<br> trueWays = lt * rt;<br> } else if (s.charAt(k) == ‘|’) {<br> trueWays =<br> lt * rt<br> + lt * rf<br> + lf * rt;<br> } else { // ^<br> trueWays =<br> lt * rf<br> + lf * rt;<br> }</p><p>long totalWays =<br> (lt + lf) * (rt + rf);</p><p>answer += wantTrue<br> ? trueWays<br> : totalWays — trueWays;</p><p>answer %= MOD;<br> }</p><p>return memo[l][r][truth] =<br> (int) answer;<br> }<br>}</p><p><em>This is the same split-DP engine with one extra state dimension: what truth value the interval must produce.</em></p><p><strong>What Changes Between the Eight?</strong></p><p><strong>Partition DP: same loop, different aggregation</strong></p><p>Minimum Difficulty<br> current = MAX(segment)<br> total = current + rest<br> answer = MIN(total)</p><p>Split Array Largest Sum<br> current = SUM(segment)<br> total = MAX(current, rest)<br> answer = MIN(total)</p><p>Partition Array for Maximum Sum<br> current = MAX(segment) × length<br> total = current + rest<br> answer = MAX(total)</p><p>Palindrome Partitioning II<br> current = 1 cut<br> total = current + rest<br> answer = MIN(total)</p><p><strong>Interval / Split DP: same split, different contribution</strong></p><p>Matrix Chain Multiplication<br> choose split k<br> cost = left + right + multiplication cost<br> aggregate = MIN</p><p>Minimum Cost to Cut a Stick<br> choose FIRST cut c<br> cost = left + right + current interval length<br> aggregate = MIN</p><p>Burst Balloons<br> choose LAST balloon i<br> coins = left + right + boundary product<br> aggregate = MAX</p><p>Boolean Parenthesization<br> choose operator split k<br> count valid truth combinations<br> aggregate = SUM</p><p><strong>Common Mistakes to Avoid</strong></p><p>Putting the temporary choice (i, c, or k) into the memoization state when it does not define a unique subproblem.</p><p>Forgetting that the recursive call starts immediately after the chosen partition endpoint.</p><p>Treating k as the number of partitions when the problem actually means maximum partition length (Partition Array for Maximum Sum).</p><p>For Minimum Difficulty, confusing “minimum sum of segment maximums” with “minimum of the maximum.”</p><p>For Matrix Chain Multiplication, using i &lt;= r as the split loop; the split is between matrices, so k runs only while k &lt; r.</p><p>For Stick Cutting, forgetting the physical boundaries 0 and n when computing the current segment length.</p><p>For Burst Balloons, choosing the first balloon without fixing its final neighbors; the last-balloon formulation makes the contribution deterministic.</p><p>For Boolean Parenthesization, forgetting that true/false is part of the state.</p><p><strong>The 20-Second Interview Checklist</strong></p><p>1. State<br> What is the smallest state?</p><p>2. Meaning<br> What does dfs(state) return?</p><p>3. Choice<br> What does the loop choose?</p><p>4. Current cost/value<br> What does this choice contribute?</p><p>5. Child states<br> What are the left/right/rest recursive calls?</p><p>6. Aggregation<br> MIN, MAX, or SUM?</p><p>7. Memo<br> Is the memo state exactly the state I just defined?</p><p>8. Optimization<br> Can I maintain a running MAX/SUM?<br> Can I remove a state dimension?</p><p><strong>The Pattern to Remember</strong></p><p><strong>Partition DP: </strong>“Choose where the current segment ends, solve the suffix, then MIN/MAX.”</p><p><strong>Interval DP: </strong>“Choose a split point (or first/last operation), solve the two intervals, then MIN/MAX/SUM.”</p><p><strong>Staff-level goal: </strong>Don’t memorize the eight recurrences independently. Be able to derive them from state → choice → contribution → child states → aggregation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05eceedbe672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search on Answer: 6 Problems to Build the Right Interview Mindset]]></title>
            <link>https://medium.com/@girishlalwani2010/binary-search-on-answer-6-problems-to-build-the-right-interview-mindset-bbee72e4e895?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbee72e4e895</guid>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[binary-search]]></category>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 20:05:48 GMT</pubDate>
            <atom:updated>2026-09-26T20:05:48.356Z</atom:updated>
            <content:encoded><![CDATA[<p>A focused Senior/Staff roadmap for recognizing feasibility, monotonicity, and answer-space search.</p><p><strong>Why this article</strong></p><p>Binary Search on Answer is easy to miss because the array does not need to be sorted. The trick is to search a numeric answer space and turn each candidate answer X into a YES/NO feasibility question. For Senior/Staff interviews, the useful skill is not memorizing a list of problems; it is recognizing that transformation quickly.</p><p>Recent public interview reports show this pattern appearing in senior-level loops. For example, a recent Google SDE2 report describes a dedicated Binary Search (on answer) round, while recent Amazon L5 reports describe Koko-style questions. These reports are candidate experiences, so they are useful signals rather than guarantees.</p><p><strong>The Recognition Pattern</strong></p><p>1. What exactly is the answer I am looking for?<br>2. What is the range of possible answers?<br>3. If I guess an answer X, can I check feasibility efficiently?<br>4. Is feasibility monotonic?<br>5. Do I want the first TRUE or the last TRUE?</p><p>The entire pattern can be reduced to this:</p><p>search space for X<br> ↓<br>check(X)<br> ↓<br>YES / NO<br> ↓<br>monotonic boundary<br> ↓<br>binary search</p><p><strong>The 6 Problems I Would Do</strong></p><p><strong>1. Koko Eating Bananas — LC 875</strong></p><p><strong>Pattern: Minimum feasible value</strong></p><p>Guess a speed and check whether all work can be finished within the deadline.</p><p><strong>2. Capacity to Ship Packages Within D Days — LC 1011</strong></p><p><strong>Pattern: Minimum capacity + greedy feasibility</strong></p><p>Guess a capacity and greedily count how many days are required.</p><p><strong>3. Minimum Number of Days to Make M Bouquets — LC 1482</strong></p><p><strong>Pattern: Binary search on time</strong></p><p>Guess a day and count how many bouquets can be formed by that day.</p><p><strong>4. Magnetic Force Between Two Balls — LC 1552</strong></p><p><strong>Pattern: Maximize the minimum distance</strong></p><p>Guess a minimum distance and greedily check whether enough balls can be placed.</p><p><strong>5. Split Array Largest Sum — LC 410</strong></p><p><strong>Pattern: Minimize the maximum + partition feasibility</strong></p><p>Guess the maximum allowed partition sum and greedily count partitions.</p><p><strong>6. Minimum Limit of Balls in a Bag — LC 1760</strong></p><p><strong>Pattern: Minimize penalty / operations</strong></p><p>Guess a per-bag limit and calculate the number of required split operations.</p><p><strong>How the 6 Problems Build the Pattern</strong></p><p><strong>1. Koko Eating Bananas: learn the basic template</strong></p><p>You are searching for the minimum eating speed. For a guessed speed X, the feasibility check is: can Koko finish all piles within H hours? If X works, every larger speed also works. That gives a monotonic FALSE → TRUE boundary.</p><p><strong>2. Ship Packages: learn greedy feasibility</strong></p><p>Now the guessed value is a shipping capacity. For a candidate capacity X, greedily pack packages in order and count how many days are required. The check is whether daysUsed &lt;= D.</p><p><strong>3. Bouquets: learn binary search on time</strong></p><p>The answer is a day. For candidate day X, count how many bouquets can be formed from flowers that have bloomed by X. If enough bouquets can be made, later days also work.</p><p><strong>4. Magnetic Force: flip the direction</strong></p><p>Here the goal is to maximize a minimum distance. Guess X and greedily place balls as far apart as required. If X is feasible, larger distances may still be possible, so the search moves right.</p><p><strong>5. Split Array Largest Sum: learn “minimize the maximum”</strong></p><p>Guess the largest sum X allowed for any partition. Scan greedily and start a new partition when adding the next value would exceed X. The feasibility check asks whether the array can be split into at most K non-empty parts.</p><p><strong>6. Balls in a Bag: generalize the idea</strong></p><p>Guess a maximum allowed number of balls in one bag. For each original bag, calculate how many split operations are required to keep every resulting bag at or below X. If total operations stay within the limit, X is feasible.</p><p><strong>The Two Big Families</strong></p><p><strong>A. Minimize X</strong></p><p>guess X<br> ↓<br>can X satisfy the constraints?<br> ↓<br>YES → try smaller<br>NO → try larger</p><p>Examples: Koko, Ship Packages, Bouquets, Split Array, Balls in a Bag.</p><p><strong>B. Maximize X</strong></p><p>guess X<br> ↓<br>can I achieve at least X?<br> ↓<br>YES → try larger<br>NO → try smaller</p><p>Example: Magnetic Force Between Two Balls.</p><p><strong>The Feasibility Function Is the Real Interview Question</strong></p><p>A common mistake is to jump directly into the binary-search loop. Instead, first write the check(X) function in plain English. If you cannot explain check(X) clearly, you are not ready to binary-search the answer.</p><p>Example: Split Array Largest Sum</p><p>check(X):<br> greedily create contiguous partitions<br> keep current sum &lt;= X<br> when adding the next value would exceed X,<br> start a new partition<br> return whether partitionsUsed &lt;= K</p><p><strong>The binary search itself is usually the easy part. The hard part is finding a monotonic feasibility check.</strong></p><p><strong>Why Some “Minimize” Problems Are Not Binary Search on Answer</strong></p><p>Seeing a minimum or maximum in the problem statement is not enough. For binary search on answer to be useful, guessing X must make the problem easier. If checking “is X feasible?” still requires solving another hard optimization or partition problem, binary search may add an outer logarithmic loop without simplifying the real work.</p><p>Good binary-search-on-answer signal:<br> guess X<br> → cheap greedy / counting / simulation check<br> → monotonic YES/NO</p><p>Weak signal:<br> guess X<br> → still need a full DP / hard optimization problem<br> → binary search does not simplify the core problem</p><p><strong>The Interview Checklist</strong></p><p>Before coding, say out loud:</p><p>1. I am binary-searching ______.<br>2. The minimum possible answer is ______.<br>3. The maximum possible answer is ______.<br>4. check(mid) means ______.<br>5. check(mid) is monotonic because ______.<br>6. I want the first TRUE / last TRUE.</p><p><strong>My Recommended Order</strong></p><p>875 Koko Eating Bananas<br> ↓<br>1011 Capacity to Ship Packages Within D Days<br> ↓<br>1482 Minimum Number of Days to Make M Bouquets<br> ↓<br>1552 Magnetic Force Between Two Balls<br> ↓<br>410 Split Array Largest Sum<br> ↓<br>1760 Minimum Limit of Balls in a Bag</p><p>Do not treat these as six isolated LeetCode questions. After each problem, write down only three things: the answer space, the feasibility check, and why the check is monotonic. That is the muscle you are actually training for Senior/Staff interviews.</p><p><strong>Interview Evidence and References</strong></p><p>Google SDE2 (Zurich) candidate report describing a dedicated Binary Search (on answer) round: <a href="https://leetcode.com/discuss/post/7623170/">https://leetcode.com/discuss/post/7623170/</a></p><p>Amazon L5 (Bangalore, May 2025) candidate report with a Koko-style round: <a href="https://leetcode.com/discuss/post/6961911/">https://leetcode.com/discuss/post/6961911/</a></p><p>Amazon L5 (Bangalore, June 2025) candidate report with a Koko-style DSA round: <a href="https://leetcode.com/discuss/post/6961860/">https://leetcode.com/discuss/post/6961860/</a></p><p>LeetCode: Koko Eating Bananas (LC 875): <a href="https://leetcode.com/problems/koko-eating-bananas/">https://leetcode.com/problems/koko-eating-bananas/</a></p><p>LeetCode discussion: Binary Search on Answer / Split Array Largest Sum pattern: <a href="https://leetcode.com/discuss/post/1503189/binary-search-split-array-largest-sum-pattern/">https://leetcode.com/discuss/post/1503189/binary-search-split-array-largest-sum-pattern/</a></p><p>LeetCode discussion: 20 Binary Search Problems to Revise Before Interviews: <a href="https://leetcode.com/discuss/post/7374749/20-binary-search-problems-to-revise-befo-hbtt/">https://leetcode.com/discuss/post/7374749/20-binary-search-problems-to-revise-befo-hbtt/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbee72e4e895" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Pattern-First DP Roadmap for Senior & Staff Software Engineer Interviews]]></title>
            <link>https://medium.com/@girishlalwani2010/a-pattern-first-dp-roadmap-for-senior-staff-software-engineer-interviews-ca74ae709221?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca74ae709221</guid>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 06:43:56 GMT</pubDate>
            <atom:updated>2026-09-30T14:36:50.411Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to build DP intuition, recognize problem families, and prepare from a compact high-signal problem set</em></p><p>Dynamic Programming is easy to study the wrong way. You can solve dozens of problems, memorize transitions, and still freeze when an interviewer changes the story. For Senior and Staff-level interviews, the more valuable skill is being able to recognize the underlying state, define what that state means, enumerate the choices, and choose the correct aggregation rule.</p><p>That is the approach behind the DP set in this article: fewer problems, deeper pattern recognition, and deliberate practice in deriving the state instead of memorizing the final code.</p><p><strong>Important: </strong>Interview reports are anecdotal signals, not guarantees. The goal is not to predict an exact interview question; it is to build a compact set of patterns that transfers to unfamiliar problems.</p><p><strong>1. The real objective: build a DP “mind state”</strong></p><p>A strong DP candidate should be able to hear a new problem and ask a small sequence of questions before writing code:</p><ol><li>What is the state?</li><li>What does f(state) mean exactly?</li><li>What choices are available from this state?</li><li>Do I want SUM, MIN, or MAX over the choices?</li><li>Can the same choice be reused?</li><li>Can I eliminate a state dimension?</li></ol><p>This is the core loop I am training:</p><p>New problem<br> ↓<br> State → meaning of f(state)<br> ↓<br> Choices → SUM / MIN / MAX<br> ↓<br> Can the choice repeat?<br> ↓<br> Can I remove a state dimension?</p><p><strong>2. Why recent interview signals matter — but only as signals</strong></p><p>Public candidate reports show that DP continues to appear in senior-level coding interviews. One Google L5 report describes a hard Dynamic Programming round; recent Amazon SDE2 reports include Word Break / Word Break II and Target Sum; and other senior-level reports show DP mixed with graphs, strings, heaps, and implementation-heavy questions. These reports are useful for prioritization, but they should not be treated as a probability model for any specific company or role.</p><p>The practical conclusion is simple: prepare the recurring DP patterns well enough that a problem can be recognized even when the surface story changes.</p><p><strong>3. The high-priority DP problem set</strong></p><p><strong>Priority</strong></p><p><strong>Problem</strong></p><p><strong>Pattern</strong></p><p>1. House Robber : Take / skip</p><p>2. Word Break: Prefix DP / variable transition</p><p>3. Coin Change: Unbounded + MIN</p><p>4. Coin Change II: Unbounded + COUNT</p><p>5. 0/1 Knapsack: Take / skip + 2D state</p><p>6. Target Sum: Counting / transformed knapsack</p><p>7. LIS: Sequence DP</p><p>8. LCS: 2D sequence DP</p><p>9. Edit Distance: 2D transformation DP</p><p>10. Decode Ways: 1D branching DP</p><p>11. Best Time to Buy/Sell Stock with Cooldown: State-machine DP</p><p>12. Distinct Subsequences: Counting DP</p><p>PARTITION DP ↓<br> 1. Minimum Difficulty of a Job Schedule <br> 2. Split Array Largest Sum <br> 3. Partition Array for Maximum Sum <br> 4. Palindrome Partitioning II ↓</p><p>INTERVAL / SPLIT DP ↓ <br>5. Matrix Chain Multiplication <br>6. Minimum Cost to Cut a Stick <br>7. Burst Balloons <br>8. Boolean Parenthesization ↓</p><p>INTERVAL / ENDPOINT DP ↓<br>9. Predict the Winner <br>10. Stone Game</p><p>13. Maximum Path Sum in Matrix / Grid DP: Grid DP</p><p>14. Interleaving String.</p><p><strong>4. Do not treat these as 15 independent problems</strong></p><p>The set becomes much more powerful when you group it by the mental pattern it is teaching.</p><p><strong>1D DP → </strong>House Robber; Decode Ways; Staircase Fee</p><p><strong>Unbounded → </strong>Coin Change; Coin Change II; Maximum Ribbon Cut</p><p><strong>0/1 → </strong>0/1 Knapsack; Subset Sum; Target Sum</p><p><strong>Sequence → </strong>LIS; LCS; Edit Distance; Distinct Subsequences</p><p><strong>State Machine → </strong>Stock problems</p><p><strong>Partition → </strong>Minimum Difficulty of a Job Schedule</p><p><strong>Interval → </strong>Burst Balloons</p><p><strong>Grid → </strong>Maximum Path Sum</p><p><strong>5. The pattern map in concrete terms</strong></p><p><strong>Coin Change → </strong>State = remaining; choice = denomination; aggregation = MIN(child + 1).</p><p><strong>Coin Change II → </strong>State = start, remaining; choice = denomination; aggregation = SUM(children).</p><p><strong>Maximum Ribbon Cut → </strong>State = remaining; choice = cut length; aggregation = MAX(child + 1).</p><p><strong>Staircase Fee → </strong>State = current step; choice = jump 1/2/3; aggregation = MIN(child + fee[current]).</p><p><strong>Minimum Jumps → </strong>State = index; choice = reachable next index; aggregation = MIN(child + 1).</p><p>The point is not the individual formula. The point is learning to see that many different stories collapse to the same state-choice-aggregation structure.</p><p><strong>6. The most useful DP aggregation rule</strong></p><p>COUNT → sum the valid child results<br> MIN → min(child + cost)<br> MAX → max(child + value)</p><p>This simple framing is especially useful when moving between closely related interview questions. The recursion skeleton stays similar; what changes is what the parent wants from its children.</p><p><strong>7. State minimization: the Senior/Staff upgrade</strong></p><p>One of the best habits at senior level is questioning whether every state dimension is actually necessary. A first solution may use f(start, remaining), but after understanding the meaning of start, you may discover that the problem can be represented by f(remaining) alone.</p><p>Before:<br> f(start, remaining)<br> <br> After:<br> f(remaining)</p><p>That is more than a small optimization. It shows that you are designing the state around the information the subproblem actually needs, rather than carrying extra context simply because it appeared in the recursion.</p><p><strong>8. What I would actually practice</strong></p><p>For Senior/Staff preparation, I would rather derive 15 representative problems deeply than memorize 50 DP solutions. The suggested sequence is:</p><p>1. House Robber — make take/skip automatic.</p><p>2. Word Break — learn prefix/state transitions.</p><p>3. Coin Change — recognize unbounded MIN.</p><p>4. Coin Change II — recognize unbounded COUNT.</p><p>5. 0/1 Knapsack — master take/skip with a 2D state.</p><p>6. Target Sum — connect counting DP to a transformed state.</p><p>7. Decode Ways — handle branching transitions cleanly.</p><p>8. LIS — practice sequence-state discovery.</p><p>9. LCS — become comfortable with 2D string states.</p><p>10. Edit Distance — model multiple edit operations as choices.</p><p>11. Distinct Subsequences — count paths through a 2D state.</p><p>12. Stock with Cooldown — model a small state machine.</p><p>13. Minimum Difficulty of a Job Schedule — learn partition DP.</p><p>14. Burst Balloons — learn interval DP.</p><p>15. Maximum Path Sum — recognize grid DP quickly.</p><p><strong>9. How to practice each problem</strong></p><p>For every problem, stop before coding and write only these three lines:</p><p>State:<br> Meaning of f(state):<br> Choice + aggregation:</p><p>Then derive the recursive solution, identify overlapping subproblems, add memoization, and only afterward ask whether the state can be compressed into a smaller bottom-up representation.</p><p>This forces the interview skill that matters most: deriving the solution under pressure instead of recalling a memorized template.</p><p><strong>10. Recent interview signals referenced</strong></p><p><strong>Google L5 SSE interview experience — </strong>Candidate report describing a hard Dynamic Programming coding round.<br> <a href="https://leetcode.com/discuss/post/4820834/Google-L5-SSE-interview-experience/">https://leetcode.com/discuss/post/4820834/Google-L5-SSE-interview-experience/</a></p><p><strong>Amazon SDE2 interview — March 2025 — </strong>Candidate report listing Word Break and Word Break II in the screening round.<br> <a href="https://leetcode.com/discuss/post/6585102/amazon-interview-sde-2-march-2025-by-ano-9nha/">https://leetcode.com/discuss/post/6585102/amazon-interview-sde-2-march-2025-by-ano-9nha/</a></p><p><strong>Amazon SDE-2 interview experience — </strong>Candidate report listing Target Sum and Word Break in DSA rounds.<br> <a href="https://leetcode.com/discuss/post/6946986/amazon-sde-2-interview-experience-by-ano-apbb/">https://leetcode.com/discuss/post/6946986/amazon-sde-2-interview-experience-by-ano-apbb/</a></p><p>Source note: these are public candidate reports. They are useful for identifying recurring signals, but they do not establish a guaranteed question set or interview probability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca74ae709221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pastebin System Design]]></title>
            <link>https://medium.com/@girishlalwani2010/pastebin-system-design-9e6eb17338d0?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e6eb17338d0</guid>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 06:14:43 GMT</pubDate>
            <atom:updated>2026-09-23T06:14:43.005Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Design Objective</h3><p>Design a scalable Pastebin-like service where users can:</p><ul><li>Create a paste.</li><li>Receive a unique short code.</li><li>Upload paste content.</li><li>Retrieve content using the short code.</li><li>Optionally specify an expiry time.</li><li>Optionally change the public short code.</li><li>Delete or expire pastes.</li><li>Store actual paste content in Object Storage rather than the application database.</li></ul><h3>Core design principle</h3><p>Separate the <strong>control plane</strong> from the <strong>data plane</strong>.</p><pre>Control Plane<br>──────────────────────────────<br>Client<br>   ↓<br>Paste Service<br>   ↓<br>Metadata DB</pre><pre>Data Plane<br>──────────────────────────────<br>Client<br>   ↓<br>OCI Object Storage</pre><p>The Paste Service manages metadata, authentication, authorization and access URLs.</p><p>The client communicates directly with Object Storage for large content.</p><h3>2. High-Level Architecture</h3><pre>┌──────────────────┐<br>                         │      Client      │<br>                         └────────┬─────────┘<br>                                  │<br>                           HTTPS + JWT<br>                                  │<br>                                  ▼<br>                         ┌──────────────────┐<br>                         │  Paste Service   │<br>                         └────────┬─────────┘<br>                                  │<br>                    ┌─────────────┼──────────────┐<br>                    │             │              │<br>                    ▼             ▼              ▼<br>             Metadata DB      ShortCode/KGS   OCI Object<br>                                             Storage<br>                                                  ▲<br>                                                  │<br>                                      Direct PUT / GET<br>                                                  │<br>                                                  ▼<br>                                               Client</pre><h3>Responsibilities</h3><p>ComponentResponsibilityClientUpload/download actual contentIdentity ProviderAuthenticate users and issue JWTPaste ServiceBusiness logic, authorization, metadata, PAR generationMetadata DBSource of truth for paste metadata and validityShortCode/KGSGenerate unique short codesOCI Object StorageStore actual paste contentObject Lifecycle ManagementAsynchronous physical cleanup</p><h3>3. Core Data Model</h3><p>The metadata DB contains information about the paste, not the actual paste content.</p><pre>content_meta<br>────────────────────────────────────────────<br>short_code       PK<br>owner_id<br>object_key<br>status<br>content_type<br>content_size<br>created_at<br>updated_at<br>expires_at</pre><p>Example:</p><pre>short_code = ABC123<br>owner_id   = user-100<br>object_key = pastes/obj-789<br>status     = COMPLETED<br>expires_at = 2026-09-25 10:00:00</pre><h3>SQL</h3><pre>CREATE TABLE content_meta (<br>    short_code      VARCHAR(32) PRIMARY KEY,<br>    owner_id        VARCHAR(128) NOT NULL,<br>    object_key      VARCHAR(512) NOT NULL,<br>    status          VARCHAR(32) NOT NULL,<br>    content_type    VARCHAR(128),<br>    content_size    BIGINT,<br>    created_at      TIMESTAMP NOT NULL,<br>    updated_at      TIMESTAMP NOT NULL,<br>    expires_at      TIMESTAMP,</pre><pre>    CONSTRAINT chk_content_status<br>        CHECK (status IN (<br>            &#39;IN_PROGRESS&#39;,<br>            &#39;COMPLETED&#39;,<br>            &#39;EXPIRED&#39;<br>        ))<br>);</pre><pre>CREATE INDEX idx_content_owner<br>    ON content_meta(owner_id);</pre><pre>CREATE INDEX idx_content_expiry<br>    ON content_meta(expires_at);</pre><h3>4. Why shortCode and objectKey Are Separate</h3><p>This is an important design decision.</p><pre>shortCode<br>    ↓<br>Business/Public Identifier</pre><pre>objectKey<br>    ↓<br>Physical Storage Identifier</pre><p>Example:</p><pre>ABC123<br>   ↓<br>content_meta<br>   ↓<br>pastes/obj-789<br>   ↓<br>OCI Object Storage</pre><p>They can initially be related:</p><pre>objectKey = &quot;pastes/&quot; + shortCode</pre><p>but they should still be modeled independently.</p><h3>Why?</h3><h4>Use Case 1 — User changes the short code</h4><pre>Before:</pre><pre>ABC123 → obj-789</pre><p>After:</p><pre>MYPASTE → obj-789</pre><p>The underlying content does not need to be moved.</p><h4>Use Case 2 — Short-code reuse</h4><p>If the product allows reuse of expired short codes:</p><pre>Old:<br>ABC123 → obj-789</pre><pre>New:<br>ABC123 → obj-456</pre><p>The old Object Storage object may still exist temporarily because physical cleanup is asynchronous.</p><p>The DB remains the source of truth for the current mapping.</p><h4>Use Case 3 — Storage migration</h4><p>The public identifier can remain stable while the physical storage location changes.</p><h3>Design principle</h3><blockquote><em>Keep the business identifier and physical storage identifier logically independent.</em></blockquote><h3>5. Object Storage Model</h3><p>The Object Storage location is conceptually:</p><pre>namespace<br>    ↓<br>bucket<br>    ↓<br>objectKey</pre><p>For example:</p><pre>namespace = mynamespace<br>bucket    = paste-content<br>objectKey = pastes/obj-789</pre><p>The bucket can be service configuration rather than duplicated in every DB row if all pastes use the same bucket.</p><p>The object key identifies the actual object within that bucket.</p><h3>Object key generation</h3><p>A random object key is not required merely because the system has millions of objects.</p><p>A simple approach is:</p><pre>objectKey = &quot;pastes/&quot; + shortCode</pre><p>or:</p><pre>objectKey = &quot;pastes/2026/09/&quot; + shortCode</pre><p>Alternatively, an independent object ID can be generated.</p><p>The important point is the <strong>logical separation</strong>, not randomness.</p><h3>6. Authentication Model</h3><p>The client first authenticates with an Identity Provider.</p><pre>Identity Provider<br>        |<br>        | JWT<br>        ▼<br>      Client<br>        |<br>        | Authorization: Bearer &lt;JWT&gt;<br>        ▼<br>   Paste Service</pre><p>The Paste Service validates the JWT and obtains the authenticated identity.</p><p>We should not trust:</p><pre>{<br>  &quot;clientId&quot;: &quot;user-123&quot;<br>}</pre><p>from the request body as proof of identity.</p><p>Instead:</p><pre>JWT<br> ↓<br>Authenticated Principal<br> ↓<br>ownerId<br> ↓<br>content_meta.owner_id</pre><h3>Authentication vs Authorization</h3><p><strong>Authentication:</strong></p><blockquote><em>Who is making this request?</em></blockquote><p><strong>Authorization:</strong></p><blockquote><em>Is this user allowed to access this paste?</em></blockquote><p>The JWT provides the authenticated identity.</p><p>The metadata DB can enforce resource ownership.</p><h3>7. POST /paste — Creation Flow</h3><pre>Client<br>  |<br>  | POST /paste<br>  | Authorization: Bearer JWT<br>  |<br>  ▼<br>Paste Service<br>  |<br>  | Validate JWT<br>  | Extract ownerId<br>  |<br>  | Generate shortCode<br>  |<br>  | Generate objectKey<br>  |<br>  | Insert metadata<br>  | status = IN_PROGRESS<br>  |<br>  | Generate temporary PUT PAR<br>  |<br>  ▼<br>Client<br>  |<br>  | Direct PUT<br>  ▼<br>OCI Object Storage</pre><p>The response contains something like:</p><pre>{<br>  &quot;shortCode&quot;: &quot;ABC123&quot;,<br>  &quot;uploadUrl&quot;: &quot;...temporary upload URL...&quot;,<br>  &quot;expiresIn&quot;: 900<br>}</pre><p>The signed upload URL is temporary and should not be persisted.</p><h3>8. Upload Completion</h3><p>After the client uploads the content:</p><pre>Client<br>   |<br>   | POST /paste/ABC123/complete<br>   ▼<br>Paste Service<br>   |<br>   | Verify object exists<br>   | Verify expected metadata/size/checksum<br>   |<br>   ▼<br>status = COMPLETED</pre><h3>Important</h3><p>Do not blindly trust:</p><pre>&quot;Client says upload succeeded&quot;</pre><p>The service should verify the object before transitioning:</p><pre>IN_PROGRESS → COMPLETED</pre><h3>9. GET /paste/{shortCode}</h3><p>This is the main read path.</p><p>Example:</p><pre>GET /paste/ABC123</pre><p>The request contains:</p><pre>shortCode = ABC123<br>JWT       = authenticated user</pre><h3>9.1 Authentication</h3><p>First validate the JWT.</p><pre>JWT<br> ↓<br>Validate signature<br> ↓<br>Validate issuer/audience/expiry/etc.<br> ↓<br>Extract userId</pre><p>With self-contained JWTs, this can generally be performed locally using the Identity Provider’s public key/JWKS.</p><p>The Paste Service does not necessarily need to call the Identity Provider for every request.</p><h3>10. GET Authorization + Lookup</h3><p>For a private paste, we can combine resource lookup and authorization into <strong>one DB query</strong>.</p><pre>SELECT<br>    object_key,<br>    status,<br>    expires_at,<br>    content_type,<br>    content_size<br>FROM content_meta<br>WHERE short_code = ?<br>  AND owner_id = ?;</pre><p>For example:</p><pre>shortCode = ABC123<br>ownerId   = user-100</pre><p>The DB query effectively asks:</p><blockquote><em>“Give me ABC123 only if it belongs to user-100.”</em></blockquote><h3>Why this is preferable</h3><p>We don’t need:</p><pre>DB call #1<br>Find ABC123</pre><pre>DB call #2<br>Check whether user owns ABC123</pre><p>Instead:</p><pre>One DB call<br>shortCode + ownerId<br>        ↓<br>Authorized row</pre><h3>11. Authentication vs Authorization in the GET Path</h3><p>The exact flow is:</p><pre>Client<br>  |<br>  | JWT + shortCode<br>  ▼<br>Paste Service<br>  |<br>  | Authenticate JWT<br>  | ↓<br>  | userId = user-100<br>  |<br>  | DB query:<br>  | WHERE shortCode = ABC123<br>  | AND ownerId = user-100<br>  |<br>  ▼<br>Metadata DB</pre><p>If the row exists:</p><pre>Authorized + Resource Found</pre><p>If no row exists:</p><pre>Resource doesn&#39;t exist<br>        OR<br>User isn&#39;t authorized</pre><p>For a private paste, the API can deliberately return the same external response for both cases, such as 404, to avoid leaking whether another user&#39;s paste exists.</p><h3>12. Public vs Private Paste</h3><p>The query depends on the access model.</p><h3>Public paste</h3><pre>WHERE short_code = ?</pre><p>Authentication may not even be required for GET.</p><h3>Private paste</h3><pre>WHERE short_code = ?<br>AND owner_id = ?</pre><h3>Shared/ACL-based paste</h3><p>The authorization model becomes more complex and may require:</p><pre>paste<br>  ↓<br>ACL / permissions<br>  ↓<br>authenticated user</pre><p>This is an open design area if sharing is required.</p><h3>13. Status and Expiry Validation</h3><p>Once the authorized row is retrieved:</p><pre>objectKey<br>status<br>expiresAt</pre><p>The service checks:</p><pre>status == COMPLETED</pre><p>and:</p><pre>expiresAt &gt; currentTime</pre><p>Example:</p><pre>expiresAt = 10:00 AM</pre><pre>GET at 09:59 → allowed<br>GET at 10:01 → rejected</pre><p>The DB expiry is the <strong>logical source of truth</strong> for whether the application should serve the paste.</p><h3>14. PAR Generation</h3><p>After successful authentication, authorization, status and expiry checks:</p><pre>shortCode<br>   ↓<br>content_meta<br>   ↓<br>objectKey<br>   ↓<br>Generate temporary GET PAR<br>   ↓<br>Return PAR</pre><p>The PAR/signed URL is generated dynamically.</p><p>It should not normally be stored in content_meta.</p><h3>Why?</h3><p>A PAR is temporary.</p><p>Instead of storing:</p><pre>signedUrl</pre><p>we store:</p><pre>objectKey</pre><p>and generate a fresh access URL whenever required.</p><h3>15. Final GET Flow</h3><pre>GET /paste/ABC123<br>        |<br>        ▼<br>   Paste Service<br>        |<br>        | Validate JWT<br>        |<br>        ▼<br>    userId = user-100<br>        |<br>        | One DB query<br>        | WHERE shortCode = ABC123<br>        | AND ownerId = user-100<br>        |<br>        ▼<br>   Metadata DB<br>        |<br>        ▼<br>   objectKey + status + expiresAt<br>        |<br>        ├── not found ───────► 404<br>        |<br>        ├── not COMPLETED ───► not ready<br>        |<br>        ├── expired ─────────► rejected<br>        |<br>        ▼<br>   Generate GET PAR<br>        |<br>        ▼<br>      Client<br>        |<br>        | Direct GET<br>        ▼<br> OCI Object Storage<br>        |<br>        ▼<br>   Paste Content</pre><p>The Paste Service does <strong>not</strong> proxy the actual content.</p><h3>16. Expiry Model</h3><p>There are two different expiry concepts.</p><h3>A. PAR expiry</h3><p>Example:</p><pre>PAR valid for 15 minutes</pre><p>This controls how long a particular temporary URL can be used.</p><p>It does <strong>not</strong> need to be stored in content_meta.</p><h3>B. Paste expiry</h3><p>Example:</p><pre>Paste expires in 2 days</pre><p>This is a product/business rule.</p><p>It should be stored:</p><pre>expires_at</pre><p>in the metadata DB.</p><p>The application stops serving the paste after that time.</p><h3>17. Object Storage Cleanup</h3><p>Logical expiry and physical deletion are different.</p><pre>DB<br>expires_at<br>   |<br>   | Application enforcement<br>   ▼<br>Paste is no longer served<br>   |<br>   | Asynchronous cleanup<br>   ▼<br>Object Storage<br>   |<br>   ▼<br>Object physically deleted</pre><p>Object Storage Lifecycle Management (OLM) can handle eventual physical cleanup.</p><h3>Important principle</h3><blockquote><em>Object existence in Object Storage does not determine whether a paste is valid.</em></blockquote><p>The metadata DB determines whether the current paste is valid.</p><h3>18. Short-Code Reuse and Asynchronous Cleanup</h3><p>Suppose:</p><pre>Old paste:</pre><pre>ABC123 → obj-789</pre><p>expires.</p><p>The DB can invalidate/delete the old mapping while:</p><pre>obj-789</pre><p>still physically exists for some time.</p><p>If short-code reuse is supported:</p><pre>New paste:</pre><pre>ABC123 → obj-456</pre><p>The old object:</p><pre>obj-789</pre><p>is irrelevant because all future lookups resolve through the current metadata mapping.</p><pre>ABC123<br>   ↓<br>Metadata DB<br>   ↓<br>obj-456</pre><p>The old obj-789 can be cleaned asynchronously.</p><p>This is another benefit of keeping shortCode and objectKey separate.</p><h3>19. Delete Flow</h3><pre>DELETE /paste/ABC123<br>        |<br>        ▼<br>Paste Service<br>        |<br>        | Authenticate<br>        | Authorize owner<br>        |<br>        ▼<br>Mark paste EXPIRED / DELETED<br>        |<br>        ▼<br>Future GETs rejected<br>        |<br>        ▼<br>Object Storage cleanup asynchronously</pre><p>We don’t necessarily need to synchronously delete the Object Storage object before making the paste inaccessible.</p><p>This keeps the control plane less coupled to Object Storage cleanup.</p><h3>20. What We Have Locked In</h3><h3>✅ Decision 1 — Object Storage for content</h3><p>Actual paste content is not stored in the relational DB.</p><h3>✅ Decision 2 — Metadata DB</h3><p>The DB stores metadata and access-control information.</p><h3>✅ Decision 3 — Short code</h3><p>shortCode is the public/business identifier.</p><h3>✅ Decision 4 — Object key</h3><p>objectKey identifies the physical Object Storage object.</p><h3>✅ Decision 5 — No persistent PAR</h3><p>Temporary PAR/signed URLs are generated dynamically.</p><h3>✅ Decision 6 — JWT authentication</h3><p>Identity comes from the validated JWT rather than a client-supplied clientId.</p><h3>✅ Decision 7 — Single-query authorization for private GET</h3><p>For private pastes:</p><pre>WHERE short_code = ?<br>AND owner_id = ?</pre><p>combines lookup and owner authorization.</p><h3>✅ Decision 8 — DB controls logical expiry</h3><p>expires_at determines whether the application will serve the paste.</p><h3>✅ Decision 9 — Object Storage handles physical cleanup</h3><p>Lifecycle management handles eventual object deletion.</p><h3>✅ Decision 10 — Direct data transfer</h3><p>Client ↔ Object Storage directly.</p><p>The Paste Service remains on the metadata/control path.</p><h3>21. Current Open Design Items</h3><p>These are the areas that still need deeper design.</p><h3>P0 — Consistency / Failure Handling</h3><p>What happens if:</p><pre>DB metadata created<br>        ↓<br>Object upload never happens</pre><p>or:</p><pre>Object upload succeeds<br>        ↓<br>DB completion update fails</pre><p>Need to design:</p><ul><li>IN_PROGRESS timeout</li><li>orphan object cleanup</li><li>reconciliation job</li><li>retry behavior</li><li>idempotent completion API</li></ul><h3>P0 — Large Uploads</h3><p>Need to decide:</p><ul><li>Maximum paste size.</li><li>Multipart upload.</li><li>Parallel upload.</li><li>Upload chunk size.</li><li>Resume failed uploads.</li><li>OCI multipart upload behavior.</li><li>How completion is tracked.</li></ul><p>For large content, the client should be able to upload directly to Object Storage without going through Paste Service.</p><h3>P0 — Short-Code Generation</h3><p>Need to finalize:</p><pre>Redis counter + Base62<br>        OR<br>KGS<br>        OR<br>Random generation + uniqueness validation</pre><p>The key requirements are:</p><ul><li>uniqueness</li><li>scalability</li><li>low latency</li><li>collision handling</li><li>failure behavior</li><li>predictable vs unpredictable identifiers</li></ul><h3>P1 — Database Scaling</h3><p>Need to determine:</p><ul><li>Expected QPS.</li><li>Read/write ratio.</li><li>DB replication.</li><li>Read replicas.</li><li>Partitioning strategy.</li><li>Hot keys.</li><li>Metadata caching.</li></ul><p>The primary GET lookup is:</p><pre>shortCode → metadata</pre><p>so the short-code access pattern should remain efficient at scale.</p><h3>P1 — Metadata Caching</h3><p>Potential architecture:</p><pre>GET<br> ↓<br>Cache<br> ↓ miss<br>DB<br> ↓<br>Cache</pre><p>But cache invalidation becomes important when:</p><ul><li>paste expires</li><li>paste is deleted</li><li>owner changes</li><li>short code changes</li></ul><h3>P1 — Object Storage Failure</h3><p>Need to define behavior when:</p><ul><li>PUT fails.</li><li>GET fails.</li><li>Object Storage is temporarily unavailable.</li><li>PAR generation fails.</li><li>Object exists but metadata says IN_PROGRESS.</li><li>Metadata says COMPLETED but object is missing.</li></ul><h3>P1 — Security / Abuse Prevention</h3><p>Need to consider:</p><ul><li>Rate limiting.</li><li>Maximum paste size.</li><li>Content scanning.</li><li>Malware/HTML/script handling.</li><li>Abuse detection.</li><li>Authentication requirements.</li><li>Public paste access.</li><li>Private paste access.</li><li>PAR permissions.</li><li>PAR lifetime.</li><li>Data exfiltration controls.</li></ul><h3>P2 — Lifecycle / Cleanup</h3><p>Need to design:</p><pre>expired DB rows<br>       +<br>orphan Object Storage objects<br>       +<br>IN_PROGRESS records</pre><p>and determine whether cleanup is:</p><ul><li>event driven</li><li>scheduled</li><li>Object Storage lifecycle based</li><li>reconciliation based</li></ul><p>A robust design will probably need both lifecycle policies and reconciliation.</p><h3>22. Design Warnings / Things to Avoid</h3><h3>⚠️ Warning 1 — Don’t store the PAR in DB</h3><p>Bad:</p><pre>shortCode → signedUrl</pre><p>Better:</p><pre>shortCode → objectKey</pre><p>Generate the temporary PAR dynamically.</p><h3>⚠️ Warning 2 — Don’t trust clientId from the request</h3><p>Bad:</p><pre>{<br>  &quot;clientId&quot;: &quot;user-123&quot;<br>}</pre><p>Use:</p><pre>JWT → authenticated userId</pre><h3>⚠️ Warning 3 — Don’t proxy large content through Paste Service</h3><p>Avoid:</p><pre>Client<br>  ↓<br>Paste Service<br>  ↓<br>Object Storage</pre><p>Prefer:</p><pre>Client<br>  ↓<br>Object Storage</pre><p>after the Paste Service authorizes access and provides a temporary access URL.</p><h3>⚠️ Warning 4 — Don’t use Object Storage existence as authorization</h3><p>This is incorrect:</p><pre>Does object exist?<br>    ↓<br>Serve it</pre><p>Instead:</p><pre>shortCode<br>   ↓<br>Metadata DB<br>   ↓<br>Authorization<br>   ↓<br>Expiry<br>   ↓<br>objectKey<br>   ↓<br>PAR</pre><h3>⚠️ Warning 5 — Client upload success is not enough</h3><p>Don’t blindly perform:</p><pre>client says &quot;upload succeeded&quot;<br>        ↓<br>status = COMPLETED</pre><p>The service should verify the object.</p><h3>⚠️ Warning 6 — Don’t assume physical deletion must be synchronous</h3><p>Logical expiry can happen immediately:</p><pre>expires_at reached<br>       ↓<br>GET rejected</pre><p>while physical cleanup happens later.</p><h3>⚠️ Warning 7 — Don’t unnecessarily perform two DB calls</h3><p>For private GET:</p><pre>❌ Query paste<br>❌ Query owner</pre><p>Prefer:</p><pre>✅ WHERE short_code = ?<br>   AND owner_id = ?</pre><p>provided the access model is owner-based.</p><h3>23. Current Core Design</h3><p>The entire system can currently be summarized as:</p><pre>CLIENT<br>                           |<br>                    JWT Authentication<br>                           |<br>                           ▼<br>                    PASTE SERVICE<br>                           |<br>              ┌────────────┴────────────┐<br>              │                         │<br>              ▼                         ▼<br>        Metadata DB                ShortCode/KGS<br>              │<br>              │<br>              │ objectKey<br>              ▼<br>       OCI Object Storage<br>              ▲<br>              │<br>       Direct PUT / GET<br>              │<br>              ▼<br>           CLIENT</pre><h3>Create</h3><pre>JWT<br> ↓<br>Authenticate<br> ↓<br>Generate shortCode<br> ↓<br>Generate objectKey<br> ↓<br>DB = IN_PROGRESS<br> ↓<br>Generate PUT PAR<br> ↓<br>Client uploads directly<br> ↓<br>Verify object<br> ↓<br>DB = COMPLETED</pre><h3>Read</h3><pre>JWT<br> ↓<br>Authenticate<br> ↓<br>shortCode + ownerId<br> ↓<br>ONE DB query<br> ↓<br>objectKey + status + expiresAt<br> ↓<br>Check status + expiry<br> ↓<br>Generate GET PAR<br> ↓<br>Client downloads directly</pre><h3>Expire</h3><pre>expires_at reached<br> ↓<br>Application stops serving<br> ↓<br>Object Storage cleanup asynchronously</pre><h3>Change short code</h3><pre>Old:<br>ABC123 → obj-789</pre><pre>New:<br>MYPASTE → obj-789</pre><p>No content movement required.</p><h3>24. Next Deep-Dive Sequence</h3><p>The architecture skeleton is now sufficiently defined.</p><p>The next design discussions should be done in this order:</p><pre>1. Consistency &amp; failure handling<br>       ↓<br>2. Multipart / parallel upload<br>       ↓<br>3. Short-code generation / KGS<br>       ↓<br>4. DB scaling + caching<br>       ↓<br>5. Cleanup / reconciliation<br>       ↓<br>6. Security + abuse prevention<br>       ↓<br>7. Capacity estimation<br>       ↓<br>8. HA / multi-region</pre><p>These are the areas most likely to turn the current HLD into a complete Staff/L6-level design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e6eb17338d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tiny URL (Latest-20-sep-2026)]]></title>
            <link>https://medium.com/@girishlalwani2010/tiny-url-latest-20-sep-2026-c2d6e5df477c?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2d6e5df477c</guid>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 15:09:48 GMT</pubDate>
            <atom:updated>2026-09-20T15:09:48.760Z</atom:updated>
            <content:encoded><![CDATA[<h3>TinyURL — Complete System Design &amp; KGS Architecture</h3><h3>1. Problem</h3><p>Design a URL-shortening service similar to TinyURL.</p><h3>Core APIs</h3><pre>POST /shorten<br>GET  /{shortCode}</pre><p>Example:</p><pre>Long URL:<br>https://example.com/products/12345</pre><pre>Short URL:<br>https://tiny.url/Ab7X9K2</pre><p>The key requirement is:</p><blockquote><em>Every generated short code must be unique.</em></blockquote><p>Other requirements:</p><ul><li>Very high read traffic</li><li>Low latency</li><li>Horizontally scalable</li><li>Highly available</li><li>Short codes should be compact</li><li>Optionally, short codes should be unpredictable</li><li>Key generation should not become a bottleneck</li></ul><h3>2. High-Level Architecture</h3><pre>┌──────────────┐<br>                         │    Client    │<br>                         └──────┬───────┘<br>                                │<br>                                ▼<br>                         ┌──────────────┐<br>                         │ API Gateway  │<br>                         └──────┬───────┘<br>                                │<br>                    ┌───────────┴───────────┐<br>                    │                       │<br>                    ▼                       ▼<br>             ┌──────────────┐       ┌──────────────┐<br>             │ URL Create   │       │ URL Redirect │<br>             │ Service      │       │ Service      │<br>             └──────┬───────┘       └──────┬───────┘<br>                    │                       │<br>                    ▼                       ▼<br>             Key Generation             Cache<br>                    │                       │<br>                    ▼                       ▼<br>                 KGS/ID                 Database<br>                    │<br>                    ▼<br>                 Database</pre><p>The read path is much hotter than the write path.</p><p>Therefore:</p><pre>CREATE → key generation → DB</pre><pre>REDIRECT → cache → DB fallback</pre><h3>3. Short-Code Generation Options</h3><p>There are three main approaches we discussed.</p><h3>Option A — Counter + Base62</h3><pre>Redis Counter<br>     ↓<br>INCRBY 1000<br>     ↓<br>Application gets range<br>     ↓<br>Local ID generation<br>     ↓<br>Base62<br>     ↓<br>Short code</pre><h3>Option B — SecureRandom + uniqueness check</h3><pre>SecureRandom<br>     ↓<br>Base62 key<br>     ↓<br>DB UNIQUE constraint<br>     ↓<br>success / retry</pre><h3>Option C — KGS</h3><pre>SecureRandom<br>     ↓<br>Bloom Filter<br>     ↓<br>Key Pool<br>     ↓<br>Application</pre><p>KGS is useful when we want to pre-generate keys so that random generation and collision handling are removed from the URL creation critical path.</p><h3>4. Counter + Base62 Design</h3><p>The simplest design is a globally increasing counter.</p><p>For example:</p><pre>Redis counter = 0</pre><p>Application servers reserve ranges.</p><pre>Server A → INCRBY 1000 → 1 - 1000</pre><pre>Server B → INCRBY 1000 → 1001 - 2000</pre><pre>Server C → INCRBY 1000 → 2001 - 3000</pre><p>Each application server keeps:</p><pre>nextId<br>maxId</pre><p>locally.</p><p>It does NOT store the entire range.</p><pre>nextId = 1<br>maxId  = 1000</pre><p>When the application needs an ID:</p><pre>id = nextId++</pre><p>Then:</p><pre>id → Base62 → shortCode</pre><h3>5. Why Allocate Ranges?</h3><p>Without range allocation:</p><pre>Every URL request<br>       ↓<br>Redis INCR<br>       ↓<br>Generate ID</pre><p>This creates a Redis operation for every URL creation.</p><p>With range allocation:</p><pre>1000 URL requests<br>       ↓<br>1 Redis INCRBY</pre><p>Therefore:</p><pre>Redis operations ↓ ~1000x</pre><p>The application generates IDs locally.</p><h3>6. Base62</h3><p>We use:</p><pre>0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz</pre><p>62 characters.</p><p>Base62 converts an integer into a compact string.</p><p>Example:</p><pre>1000 → G8</pre><p>Java implementation:</p><pre>public class Base62 {</pre><pre>    private static final String CHARACTERS =<br>            &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&quot;;</pre><pre>    public static String encode(long number) {</pre><pre>        if (number == 0) {<br>            return &quot;0&quot;;<br>        }</pre><pre>        StringBuilder result = new StringBuilder();</pre><pre>        while (number &gt; 0) {</pre><pre>            int remainder = (int) (number % 62);</pre><pre>            result.append(<br>                    CHARACTERS.charAt(remainder)<br>            );</pre><pre>            number /= 62;<br>        }</pre><pre>        return result.reverse().toString();<br>    }<br>}</pre><h3>7. Base62 Capacity</h3><p>The number of possible codes is:</p><pre>62^N</pre><p>Approximate capacity:</p><p>LengthCapacity5~916 million6~56.8 billion7~3.52 trillion8~218 trillion</p><p>Therefore, a 7–8 character key space is enormous for a typical TinyURL deployment.</p><p>However:</p><blockquote><em>A large key space makes collisions unlikely; it does not mathematically eliminate collisions when keys are randomly generated.</em></blockquote><h3>8. Counter vs Random Keys</h3><p>Counter-based IDs:</p><pre>1<br>2<br>3<br>4<br>5<br>...</pre><p>Base62:</p><pre>1<br>2<br>3<br>4<br>5<br>...</pre><p>Advantages:</p><ul><li>No collision</li><li>Very simple</li><li>Fast</li><li>Easy to scale with range allocation</li></ul><p>Disadvantage:</p><ul><li>Predictable</li></ul><p>Someone can potentially enumerate:</p><pre>abc123<br>abc124<br>abc125</pre><p>If unpredictability matters, use random keys.</p><h3>9. SecureRandom</h3><p>Java:</p><pre>SecureRandom random = new SecureRandom();</pre><p>It generates cryptographically strong pseudo-random values.</p><p>Important distinction:</p><pre>Random<br>    ↓<br>ordinary randomness</pre><pre>SecureRandom<br>    ↓<br>unpredictable randomness</pre><p>SecureRandom does <strong>not</strong> guarantee uniqueness.</p><p>Two calls can theoretically produce the same value.</p><p>So:</p><blockquote><em>SecureRandom provides unpredictability, not uniqueness.</em></blockquote><h3>10. Random Key Generation</h3><p>Conceptually:</p><pre>SecureRandom<br>      ↓<br>Random value<br>      ↓<br>Base62<br>      ↓<br>Short code</pre><p>For example:</p><pre>SecureRandom<br>     ↓<br>837492...<br>     ↓<br>Base62<br>     ↓<br>Ab7X9K2</pre><p>With a sufficiently large key space, collisions become very unlikely.</p><h3>11. Hashing Is Different</h3><p>A hash is not a uniqueness mechanism.</p><p>For example:</p><pre>URL A → SHA-256 → X<br>URL B → SHA-256 → X</pre><p>A collision is theoretically possible because the output space is finite.</p><p>Therefore:</p><pre>Hash ≠ uniqueness guarantee</pre><p>If hashing is used, the authoritative store must still handle collisions.</p><h3>12. KGS — Key Generation Service</h3><p>KGS stands for:</p><blockquote><em>Key Generation Service</em></blockquote><p>Instead of generating a random key during every URL creation request, KGS generates keys <strong>ahead of time</strong>.</p><p>Architecture:</p><pre>KGS<br>                  │<br>           SecureRandom<br>                  │<br>                  ▼<br>           Generate key<br>                  │<br>                  ▼<br>           Bloom Filter<br>                  │<br>                  ▼<br>          Key uniqueness<br>                  │<br>                  ▼<br>             Key Pool<br>                  │<br>          batch allocation<br>                  │<br>                  ▼<br>            Application</pre><p>The objective is:</p><blockquote><em>Move key generation and collision handling away from the request path.</em></blockquote><h3>13. Why KGS?</h3><p>Without KGS:</p><pre>POST /shorten<br>       ↓<br>Generate random key<br>       ↓<br>Check collision<br>       ↓<br>Retry if necessary<br>       ↓<br>Store URL</pre><p>With KGS:</p><pre>Background KGS<br>      ↓<br>Generate millions of keys<br>      ↓<br>Keep them ready</pre><pre>POST /shorten<br>      ↓<br>Take existing key<br>      ↓<br>Store URL</pre><p>Therefore URL creation becomes faster and more predictable.</p><h3>14. KGS Key Pool</h3><p>The important distinction:</p><h3>KGS Key Pool</h3><p>Global pool of generated and available keys.</p><pre>KGS<br> │<br> ▼<br>┌──────────────────────┐<br>│ K1 K2 K3 ... K100000 │<br>└──────────────────────┘</pre><h3>Application Key Buffer</h3><p>Application can lease a batch:</p><pre>KGS<br> │<br> │ getKeys(1000)<br> ▼<br>Application<br> │<br> ▼<br>Local buffer:<br>K1 K2 K3 ... K1000</pre><p>The application then consumes keys locally.</p><h3>15. Batch Allocation</h3><p>Instead of:</p><pre>Request 1 → KGS<br>Request 2 → KGS<br>Request 3 → KGS<br>...</pre><p>use:</p><pre>Application<br>      │<br>      │ getKeys(1000)<br>      ▼<br>     KGS<br>      │<br>      └── K1 ... K1000<br>               │<br>               ▼<br>        Application buffer</pre><p>Then:</p><pre>Request 1 → K1<br>Request 2 → K2<br>Request 3 → K3<br>...</pre><p>When the buffer becomes low:</p><pre>remaining = 200<br>       ↓<br>request another 1000</pre><p>This removes KGS from the critical path for individual requests.</p><h3>16. Where Does the KeyPool Live?</h3><p>The authoritative pool belongs to <strong>KGS</strong>.</p><p>Production architecture:</p><pre>KGS-1<br>                │<br>              KGS-2<br>                │<br>              KGS-3<br>                │<br>                ▼<br>        ┌─────────────────┐<br>        │      Redis      │<br>        │                 │<br>        │ Available Keys  │<br>        └────────┬────────┘<br>                 │<br>            batch allocation<br>                 │<br>                 ▼<br>           Application<br>          Local Buffer</pre><p>Applications may have a local buffer, but that is not the authoritative KGS pool.</p><h3>17. Redis Key Pool</h3><p>Redis can maintain the available-key pool.</p><p>Conceptually:</p><pre>Redis</pre><pre>kgs:available<br>--------------------------------<br>K1<br>K2<br>K3<br>K4<br>...</pre><p>Application requests a batch.</p><p>Modern Redis supports set-pop operations such as:</p><pre>SPOP kgs:available 1000</pre><p>The keys are removed from the available pool and returned to the application.</p><h3>18. Why Is Losing a Key Acceptable?</h3><p>Suppose:</p><pre>KGS → Application<br>       ↓<br>    K1...K1000</pre><p>Application crashes after receiving them.</p><p>Some keys may never be used.</p><p>We do not need to return them.</p><p>This creates:</p><pre>unused keys / gaps</pre><p>but not duplicates.</p><p>For TinyURL:</p><blockquote><em>Uniqueness is important; contiguous utilization is not.</em></blockquote><p>Therefore burning unused keys is generally acceptable.</p><h3>19. Bloom Filter</h3><p>A Bloom Filter is used as a memory-efficient probabilistic membership structure.</p><p>Conceptually:</p><pre>Bloom Filter<br>--------------------------------<br>0 1 0 1 1 0 0 1 0 1 1 0 ...</pre><p>It does not store the actual keys.</p><p>It stores bits.</p><h3>20. Bloom Filter Semantics</h3><p>The fundamental rule:</p><pre>Bloom = false<br>    ↓<br>Definitely NOT present</pre><p>But:</p><pre>Bloom = true<br>    ↓<br>MAY be present</pre><p>Therefore:</p><pre>false → guaranteed absent</pre><pre>true → possibly present</pre><p>A standard Bloom Filter has:</p><blockquote><em>False positives, but no false negatives.</em></blockquote><h3>21. False Positive</h3><p>Suppose:</p><pre>Key A → bits 10, 50, 90<br>Key B → bits 20, 50, 70</pre><p>Those bits are now set.</p><p>A new key C may hash to:</p><pre>10, 50, 70</pre><p>All those bits are already 1.</p><p>Bloom Filter says:</p><pre>C → PRESENT</pre><p>But C may never have been inserted.</p><p>That’s a false positive.</p><h3>22. KGS Can Discard Bloom Positives</h3><p>For our KGS use case, we can exploit this.</p><p>Suppose:</p><pre>Generate random key<br>       ↓<br>Bloom Filter<br>       ↓<br>     YES</pre><p>Instead of checking the authoritative store, we can simply:</p><pre>discard candidate<br>       ↓<br>generate another key</pre><p>Why is this safe?</p><p>Because both possibilities are safe:</p><pre>Bloom YES</pre><pre>1. Key actually exists<br>       → discard</pre><pre>2. False positive<br>       → discard unused candidate</pre><p>We only waste a random candidate.</p><p>Therefore:</p><pre>SecureRandom<br>     ↓<br>Bloom Filter<br>     ↓<br> ┌───┴────┐<br>NO       YES<br> ↓         ↓<br>accept   discard<br> ↓         ↓<br>add      retry<br> ↓<br>Key Pool</pre><p>This can avoid an expensive existence lookup on the generation path.</p><h3>23. Important Bloom Filter Caveat</h3><p>The Bloom Filter is an optimization.</p><p>For a production design, correctness across:</p><ul><li>KGS restarts</li><li>Bloom Filter loss</li><li>multiple KGS instances</li><li>stale/rebuilt filters</li><li>persistence failures</li></ul><p>requires careful handling.</p><p>If the Bloom Filter is reconstructed incorrectly or loses information, it can no longer safely act as the sole uniqueness authority.</p><p>Therefore the strongest architecture is:</p><pre>Bloom Filter<br>     ↓<br>optimization<br>     ↓<br>Authoritative uniqueness mechanism</pre><p>The authoritative mechanism can be:</p><pre>Redis<br>PostgreSQL<br>Distributed key store</pre><p>depending on the design.</p><h3>24. Bloom Filter From Scratch</h3><p>A basic Bloom Filter contains:</p><pre>BitSet<br>+<br>Hash functions</pre><p>Java POC:</p><pre>import java.nio.charset.StandardCharsets;<br>import java.util.BitSet;</pre><pre>public class BloomFilter {</pre><pre>    private final BitSet bits;<br>    private final int size;<br>    private final int numHashFunctions;</pre><pre>    public BloomFilter(int size, int numHashFunctions) {<br>        this.size = size;<br>        this.numHashFunctions = numHashFunctions;<br>        this.bits = new BitSet(size);<br>    }</pre><pre>    public void add(String key) {</pre><pre>        for (int i = 0; i &lt; numHashFunctions; i++) {</pre><pre>            int index = hash(key, i);</pre><pre>            bits.set(index);<br>        }<br>    }</pre><pre>    public boolean mightContain(String key) {</pre><pre>        for (int i = 0; i &lt; numHashFunctions; i++) {</pre><pre>            int index = hash(key, i);</pre><pre>            if (!bits.get(index)) {<br>                return false;<br>            }<br>        }</pre><pre>        return true;<br>    }</pre><pre>    private int hash(String key, int seed) {</pre><pre>        byte[] bytes =<br>                key.getBytes(StandardCharsets.UTF_8);</pre><pre>        int hash = seed;</pre><pre>        for (byte b : bytes) {<br>            hash = 31 * hash + b;<br>        }</pre><pre>        return Math.floorMod(hash, size);<br>    }<br>}</pre><p>This is a learning POC.</p><p>For production, use a well-tested implementation such as Guava or a specialized distributed/probabilistic data structure.</p><h3>25. Number of Keys vs Number of Bits</h3><p>They are different.</p><pre>n = expected number of keys</pre><pre>m = number of bits</pre><p>Example:</p><pre>Expected keys = 1,000,000</pre><pre>Bloom Filter<br>    ↓<br>~9.6 million bits</pre><p>For a 1% false-positive probability:</p><pre>m ≈ 9.6 million bits</pre><p>approximately:</p><pre>1.2 MB</pre><p>The required size depends on the desired false-positive probability.</p><h3>26. Bloom Filter Formulas</h3><p>Approximate number of bits:</p><pre>m = -n ln(p) / (ln 2)^2</pre><p>where:</p><pre>n = expected number of keys<br>p = desired false-positive probability</pre><p>Optimal number of hash functions:</p><pre>k = (m / n) ln 2</pre><p>Example:</p><pre>n = 1,000,000<br>p = 0.01</pre><pre>m ≈ 9.6 million bits<br>k ≈ 7</pre><h3>27. KGS Production Architecture</h3><p>A scalable design can look like:</p><pre>┌──────────────┐<br>                       │ Applications │<br>                       └──────┬───────┘<br>                              │<br>                       getKeys(1000)<br>                              │<br>                              ▼<br>                 ┌─────────────────────┐<br>                 │        KGS           │<br>                 │                     │<br>                 │ SecureRandom        │<br>                 │ Bloom Filter        │<br>                 │ Pool Manager        │<br>                 └──────────┬──────────┘<br>                            │<br>                            ▼<br>                     ┌─────────────┐<br>                     │    Redis    │<br>                     │             │<br>                     │ Key Pool    │<br>                     │ Uniqueness  │<br>                     └─────────────┘</pre><p>Multiple KGS instances can run:</p><pre>KGS-1 ─┐<br>KGS-2 ─┼──→ Redis<br>KGS-3 ─┘</pre><p>They share the global key state.</p><h3>28. KGS Pool Replenishment</h3><p>Don’t wait until the pool becomes empty.</p><p>Use:</p><pre>High Watermark = 1,000,000<br>Low Watermark  =   200,000</pre><p>Background replenishment:</p><pre>Pool size &gt; 200K<br>      ↓<br>No action</pre><pre>Pool size &lt;= 200K<br>      ↓<br>Generate more keys<br>      ↓<br>Refill pool</pre><p>This prevents request failures due to an empty pool.</p><h3>29. Application Buffer Replenishment</h3><p>Similarly:</p><pre>Application buffer = 1000</pre><p>Set:</p><pre>Low watermark = 200</pre><p>Then:</p><pre>1000 → 999 → ... → 200<br>                     ↓<br>              request another 1000</pre><p>This can be done asynchronously so the request path doesn’t wait.</p><h3>30. Failure Handling</h3><h3>KGS crashes</h3><p>Other KGS instances continue generating keys.</p><pre>KGS-1 ❌</pre><pre>KGS-2 ─┐<br>KGS-3 ─┼──→ Redis</pre><h3>Application crashes</h3><p>Its leased keys may be lost.</p><p>That’s acceptable.</p><h3>Redis unavailable</h3><p>KGS cannot safely coordinate the shared pool.</p><p>Possible approaches:</p><ul><li>Fail generation temporarily</li><li>Use a local emergency buffer</li><li>Recover after Redis becomes available</li></ul><p>Do not generate blindly if Redis is the authoritative uniqueness mechanism.</p><h3>Bloom Filter restart</h3><p>An in-memory Bloom Filter disappears.</p><p>Options:</p><pre>1. Rebuild from authoritative store<br>2. Persist the filter<br>3. Warm asynchronously<br>4. Temporarily rely on authoritative checks</pre><h3>31. KGS vs Redis Counter</h3><p>FeatureRedis CounterKGSKey typeSequentialRandomPredictableYesNoCollisionNone for allocated IDsPossible during generationComplexityLowHigherRedis coordinationRange allocationShared key poolRequest pathVery fastVery fastPre-generationNoYesBloom FilterNot requiredUsefulKey gapsPossiblePossibleBest useSimple unique IDsRandom/unpredictable IDs</p><h3>32. Which Design Should We Choose?</h3><h3>If predictability is acceptable</h3><p>Use:</p><pre>Redis INCRBY<br>      ↓<br>Local ID range<br>      ↓<br>Base62</pre><p>This is the simplest architecture.</p><h3>If unpredictability is required</h3><p>Use:</p><pre>SecureRandom<br>      ↓<br>large key space<br>      ↓<br>uniqueness mechanism</pre><h3>If scale is extremely high and we don’t want generation work on the request path</h3><p>Use:</p><pre>KGS<br> │<br> ├── SecureRandom<br> ├── Bloom Filter<br> ├── Key Pool<br> └── Redis / DB<br>       ↓<br>Application batch<br>       ↓<br>Local buffer</pre><h3>33. KGS Is Not Mandatory</h3><p>This is an important Staff-level design point.</p><p>KGS is an <strong>optimization/architecture choice</strong>, not a fundamental requirement.</p><p>You can build TinyURL without KGS:</p><pre>Request<br>   ↓<br>SecureRandom<br>   ↓<br>DB UNIQUE<br>   ↓<br>success / retry</pre><p>KGS becomes useful when we want:</p><ul><li>predictable creation latency</li><li>high write throughput</li><li>pre-generation</li><li>random/unpredictable keys</li><li>collision work moved out of request processing</li></ul><h3>34. Redis Counter vs KGS — Key Insight</h3><p>The two approaches solve slightly different problems.</p><h3>Redis Counter</h3><p>Solves:</p><blockquote><em>How do I guarantee globally unique IDs efficiently?</em></blockquote><pre>INCRBY 1000</pre><h3>KGS</h3><p>Solves:</p><blockquote><em>How do I have a large supply of random, already-verified keys ready before requests arrive?</em></blockquote><pre>generate ahead<br>    ↓<br>verify<br>    ↓<br>pool<br>    ↓<br>consume</pre><h3>35. Strong L6 Interview Answer</h3><p>A concise answer for the interview:</p><blockquote><em>“For TinyURL, I would first decide whether the short code needs to be unpredictable. If predictability is acceptable, I’d use a Redis atomic counter with range allocation — each application instance reserves, say, 1,000 IDs using INCRBY and generates Base62 locally. This gives uniqueness without a Redis call per request.</em></blockquote><blockquote><em>If the short codes need to be unpredictable, I’d use SecureRandom with a sufficiently large key space. At higher scale, I’d introduce a Key Generation Service that pre-generates random keys and maintains an available-key pool. A Bloom Filter can efficiently reject candidates that may already have been generated; because false positives are safe to discard, we can avoid an authoritative lookup on every candidate, provided we have an appropriate durable uniqueness strategy for the overall system.</em></blockquote><blockquote><em>Applications lease keys from KGS in batches, for example 1,000 at a time, and maintain a local buffer. This keeps KGS and random generation off the critical path for individual URL creation requests.”</em></blockquote><h3>36. Final Mental Model</h3><p>Remember TinyURL as:</p><pre>TINYURL<br>                     │<br>          ┌──────────┴──────────┐<br>          │                     │<br>       CREATE                REDIRECT<br>          │                     │<br>          ▼                     ▼<br>    Key Generation            Cache<br>          │                     │<br>     ┌────┴────┐                │<br>     │         │                │<br> Counter      KGS                │<br>     │         │                │<br> Base62   SecureRandom           │<br>              │                 │<br>          Bloom Filter           │<br>              │                 │<br>          Key Pool               │<br>              │                 │<br>        Batch → App              │<br>              │                 │<br>              └────────┬────────┘<br>                       ▼<br>                    Database</pre><p>The three most important design decisions are:</p><pre>1. Sequential or random keys?<br>2. Direct generation or KGS?<br>3. Where is uniqueness guaranteed?</pre><p>Those three decisions drive most of the TinyURL/KGS architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2d6e5df477c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis HA (w Sentinel, in 3 Nodes Set-up)]]></title>
            <link>https://medium.com/@girishlalwani2010/redis-ha-w-sentinel-in-3-nodes-set-up-5957640c15dc?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5957640c15dc</guid>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 17:28:55 GMT</pubDate>
            <atom:updated>2026-09-13T17:56:02.863Z</atom:updated>
            <content:encoded><![CDATA[<p>Summary of doc:</p><pre>RedisURI redisURI = RedisURI.builder()<br>        .withSentinel(&quot;localhost&quot;, 26379)<br>        .withSentinel(&quot;localhost&quot;, 26380)<br>        .withSentinel(&quot;localhost&quot;, 26381)<br>        .withSentinelMasterId(&quot;mymaster&quot;)<br>        .build();<br>// stores the sentinel configuration, configure the discovery.<br>RedisClient client = RedisClient.create(redisURI);</pre><pre>RedisClient client = RedisClient.create(redisURI);<br>//Configure client with sentinel and all server-nodes<br>// sentinel can be a process inside each server node or on different node.</pre><pre>StatefulRedisConnection&lt;String, String&gt; connection = client.connect();<br>//client.connect() → connect client with redis master.<br><br>and if set/get or any operations fails due to failover, application can retry<br>that operation if it is idempotent.</pre><p>What Happens during Failover not exact but on highlevel good to remember:</p><ul><li>Sentinel select new Master.</li><li>Sentinel sends master-watch event to lettuce.</li><li>lettuce update master conf on master-watch event, and rebuild the connection with new master behind the scene, client not need to call client.connect() again.</li><li>and if client in application layer retries for same operation, it will go to new master.</li></ul><h3>Redis HA, Failover &amp; Scaling</h3><h3>6. Redis HA — Master / Replica</h3><p>A common Redis HA setup is:</p><pre>Master<br>                |<br>         asynchronous<br>         replication<br>                ↓<br>             Replica</pre><ul><li><strong>Master</strong> handles writes.</li><li><strong>Replica</strong> copies data from the master.</li><li>Replica can also serve reads if the application allows stale/eventually consistent data.</li><li>Replication is generally <strong>asynchronous</strong>, so there can be replication lag.</li></ul><h3>Why replication?</h3><p>Primarily for:</p><ul><li>High availability</li><li>Failover</li><li>Read scaling</li></ul><p>Replication alone does <strong>not</strong> automatically provide failover.</p><p>If the master dies, something needs to detect the failure and promote a replica.</p><h3>7. Redis Sentinel</h3><p>Sentinel provides:</p><ul><li>Master monitoring</li><li>Failure detection</li><li>Master discovery</li><li>Failover coordination</li><li>Replica promotion</li><li>Notification of master changes</li></ul><p>Typical setup:</p><pre>Sentinel 1<br>                 |<br>             Sentinel 2<br>                 |<br>             Sentinel 3<br>                 |<br>                 ↓<br>              Master<br>                 |<br>             Replica</pre><p>Sentinel is <strong>not a proxy</strong>.</p><p>Redis commands don’t normally flow through Sentinel:</p><pre>❌ Application → Sentinel → Redis</pre><p>Instead:</p><pre>Application<br>     |<br>   Lettuce<br>     |<br>     └────────────→ Redis Master</pre><p>Sentinel is mainly part of the <strong>control/discovery plane</strong>.</p><h3>8. Sentinel Master Discovery</h3><p>Sentinel maintains information about the monitored master.</p><p>Conceptually:</p><pre>mymaster → redis-master:6379</pre><p>Lettuce can ask Sentinel:</p><pre>SENTINEL get-master-addr-by-name mymaster</pre><p>and receive:</p><pre>redis-master<br>6379</pre><p>After failover:</p><pre>mymaster → redis-replica:6379</pre><p>So the mapping changes when a new master is promoted.</p><h3>9. Lettuce + Sentinel</h3><p>Application config:</p><pre>RedisURI redisURI = RedisURI.builder()<br>        .withSentinel(&quot;localhost&quot;, 26379)<br>        .withSentinel(&quot;localhost&quot;, 26380)<br>        .withSentinel(&quot;localhost&quot;, 26381)<br>        .withSentinelMasterId(&quot;mymaster&quot;)<br>        .build();</pre><pre>RedisClient client = RedisClient.create(redisURI);</pre><pre>StatefulRedisConnection&lt;String, String&gt; connection =<br>        client.connect();</pre><pre>RedisCommands&lt;String, String&gt; redis =<br>        connection.sync();</pre><h3>Initial connection</h3><p>Conceptually:</p><pre>client.connect()<br>       ↓<br>Lettuce<br>       ↓<br>Sentinel<br>       ↓<br>&quot;Who is mymaster?&quot;<br>       ↓<br>Master A<br>       ↓<br>Lettuce connects to Master A</pre><p>After connection, normal commands:</p><pre>redis.get(&quot;key&quot;);<br>redis.set(&quot;key&quot;, &quot;value&quot;);</pre><p>go directly through the Redis connection.</p><p>There is <strong>no Sentinel lookup before every GET/SET</strong>.</p><h3>10. What Happens When Master Dies?</h3><p>Initially:</p><pre>Lettuce ─────────→ Master A</pre><p>Master A fails:</p><pre>Lettuce ───────X──→ Master A</pre><p>Sentinel detects the failure and coordinates failover:</p><pre>Master A ❌<br>    ↓<br>Sentinel detects failure<br>    ↓<br>Replica B promoted<br>    ↓<br>B becomes new Master</pre><p>Sentinel’s view becomes:</p><pre>mymaster → Master B</pre><p>Lettuce’s Sentinel-aware connection handling learns the new master and establishes a new Redis connection.</p><pre>Old:</pre><pre>Lettuce ─────→ Master A ❌<br></pre><pre>New:</pre><pre>Lettuce ─────→ Master B</pre><p>The application does <strong>not</strong> normally call:</p><pre>client.connect();</pre><p>again.</p><p>Lettuce handles connection recovery internally.</p><h3>11. ConnectionWatchdog</h3><p>Lettuce has internal connection/reconnection machinery, including the <strong>ConnectionWatchdog</strong>.</p><p>Its responsibility is primarily around connection/channel failure and reconnection.</p><p>Conceptually:</p><pre>Redis connection<br>      ↓<br>Channel becomes inactive<br>      ↓<br>ConnectionWatchdog /<br>reconnection machinery<br>      ↓<br>New connection</pre><p>Don’t think:</p><blockquote><em>ConnectionWatchdog decides who the new master is.</em></blockquote><p>Instead:</p><pre>Sentinel<br>   ↓<br>Current master information</pre><pre>Lettuce connection machinery<br>   ↓<br>Establish connection</pre><p>These are separate responsibilities.</p><h3>12. Connection Recovery ≠ Command Retry</h3><p>This is critical.</p><p>Suppose:</p><pre>SET X = 100<br>     ↓<br>Master A<br>     ↓<br>Master dies</pre><p>There are multiple possibilities.</p><h3>Command never reached Redis</h3><pre>Client → X → Master</pre><h3>Command executed but response was lost</h3><pre>Client → SET → Redis<br>              ↓<br>           executed<br>              ↓<br>          response X</pre><p>The client may only know:</p><pre>&quot;Connection failed.&quot;</pre><p>It may <strong>not know whether the command executed</strong>.</p><p>Therefore:</p><pre>Connection recovery<br>        ≠<br>Command retry</pre><h3>13. Application-Level Retry</h3><p>Example:</p><pre>try {<br>    redis.set(key, value);<br>} catch (Exception e) {<br>    // application decides what to do<br>}</pre><p>If your application retries:</p><pre>SET X = 100<br>    ↓<br>Master executes<br>    ↓<br>Response lost<br>    ↓<br>Client sees exception<br>    ↓<br>Application retries<br>    ↓<br>SET X = 100 again</pre><p>For SET, repeating the same value is generally idempotent.</p><p>But:</p><pre>INCR counter</pre><p>is different:</p><pre>INCR<br> ↓<br>counter = 101<br> ↓<br>response lost<br> ↓<br>retry<br> ↓<br>counter = 102</pre><p>So blindly retrying non-idempotent operations can produce incorrect results.</p><h3>14. Replication Lag and Data Loss</h3><p>Redis replication is generally asynchronous.</p><pre>Client<br>  |<br>  ↓<br>Master<br>  |<br>  | async replication<br>  ↓<br>Replica</pre><p>Suppose:</p><pre>Client → Master: WRITE<br>             |<br>             X<br>          Master dies<br>             |<br>             ↓<br>Replica may not have received WRITE</pre><p>After failover:</p><pre>Replica → New Master</pre><p>The latest write may be missing.</p><p>Therefore HA does <strong>not</strong> automatically mean zero data loss.</p><p>You need to ask:</p><blockquote><strong><em>Can this workload tolerate losing writes that had not reached the replica?</em></strong></blockquote><h3>15. Redis Scaling</h3><p>Separate <strong>HA</strong> from <strong>horizontal scaling</strong>.</p><h3>Replication</h3><p>Primarily:</p><pre>HA + read scaling</pre><pre>Master<br>  ↓<br>Replica</pre><h3>Sharding</h3><p>Primarily:</p><pre>Distribute data + memory + write load</pre><pre>Redis Cluster</pre><pre>Node A     Node B     Node C<br>  ↓          ↓          ↓<br>Keys       Keys       Keys</pre><p>Each node owns a subset of the keyspace.</p><h3>16. Redis Cluster and Hash Slots</h3><p>Redis Cluster uses <strong>hash slots</strong>.</p><p>Conceptually:</p><pre>key<br> ↓<br>CRC16<br> ↓<br>16384 hash slots<br> ↓<br>Redis node</pre><p>Example:</p><pre>metadata:123<br>     ↓<br>hash<br>     ↓<br>slot 5211<br>     ↓<br>Node B</pre><p>This is different from saying Redis Cluster uses the traditional <strong>consistent-hashing ring</strong> model.</p><h3>17. Hot Keys</h3><p>A hot key is a key receiving disproportionately high traffic.</p><pre>1 key<br>               ↓<br>          huge traffic<br>               ↓<br>          one shard<br>               ↓<br>           bottleneck</pre><p>Important:</p><blockquote><strong><em>Sharding does not automatically solve a hot key.</em></strong></blockquote><p>The same key still maps to the same shard.</p><p>Possible approaches:</p><ul><li>Local caching</li><li>Key splitting</li><li>Replication</li><li>Request coalescing</li><li>Redesign access pattern</li></ul><p>Each introduces consistency/complexity trade-offs.</p><h3>18. Redis Memory</h3><p>Memory planning should include more than just value size.</p><p>Conceptually:</p><pre>Redis memory<br>=<br>keys<br>+ values<br>+ object overhead<br>+ replication buffers<br>+ client buffers<br>+ fragmentation<br>+ operational headroom</pre><p>A workload with millions of tiny keys can consume significantly more memory than the raw payload size suggests.</p><p>Monitor:</p><ul><li>Memory usage</li><li>Memory fragmentation</li><li>Evictions</li><li>Hit ratio</li><li>Key cardinality</li><li>Hot keys</li><li>Latency</li></ul><h3>19. Redis Failure Handling</h3><p>Always discuss what happens when Redis is unavailable.</p><pre>Application<br>     ↓<br>Redis ❌</pre><p>Possible strategies:</p><h3>Cache</h3><p>Fallback to DB:</p><pre>Redis ❌<br>   ↓<br>DB</pre><h3>Metadata</h3><p>Depending on requirements:</p><ul><li>fallback to DB</li><li>serve stale data</li><li>fail request</li><li>rebuild Redis</li></ul><h3>Critical data</h3><p>Need to consider:</p><ul><li>replication</li><li>persistence</li><li>durability</li><li>failover</li><li>replication lag</li><li>possible data loss</li></ul><h3>20. L6 Redis HA Mental Model</h3><p>Keep these responsibilities separate:</p><pre>Redis HA<br>                     |<br>        ┌────────────┼────────────┐<br>        ↓            ↓            ↓<br>  Replication     Sentinel     Reconnect<br>        |            |            |<br>   copies data    detects &amp;      restores<br>                  promotes       connection</pre><p>And the most important distinction:</p><pre>Connection recovery<br>        ≠<br>Command retry<br>        ≠<br>Exactly-once execution</pre><p>For an L6 interview, this distinction is more important than remembering individual Redis commands.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5957640c15dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Patterns for below 9 Data Structure Design problems]]></title>
            <link>https://medium.com/@girishlalwani2010/patterns-for-below-9-data-structure-design-problems-bd240a645a7e?source=rss-2f2df87f87cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd240a645a7e</guid>
            <dc:creator><![CDATA[Girishlalwani]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 14:27:21 GMT</pubDate>
            <atom:updated>2026-08-09T14:40:36.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkV-V3O_t15OSvliw2_zeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLfOxvfYLCIegJbWuXIPAg.png" /></figure><p>Here are the <strong>9 Data Structure Design problems</strong> we covered, in the order we studied them:</p><p>#ProblemCore Pattern Learned<br><strong>1. Min Stack </strong>Historical State (maintain running minimum)<br><strong>2. Insert Delete GetRandom O(1)</strong> (Randomized Set)Multiple Representations (ArrayList + HashMap)<br><strong>3. LRU Cache </strong>Identity + Ordering (HashMap + Doubly Linked List)<br><strong>4. Number Containers System </strong>Forward + Reverse Index (index→number, number→sorted indices)<br><strong>5. All O`one Data Structure </strong>Dynamic Buckets (DLL of count buckets + HashMap)<br><strong>6. LFU Cache </strong>Buckets + Ordering (Frequency buckets + LRU within each bucket)<br><strong>7. Max Stack </strong>Multiple Independent Orderings (Stack order + Value order)<br><strong>8. Stock Price Fluctuation </strong>Mutable Secondary Index (update indexed values efficiently)<br><strong>9. Design a Food Rating System </strong>Mutable Ordered Objects (Objects stored in ordered groups)</p><h3>The evolution of patterns</h3><pre>1. Min Stack<br>   ↓<br>Historical State</pre><pre>2. Randomized Set<br>   ↓<br>Multiple Representations</pre><pre>3. LRU Cache<br>   ↓<br>Identity + Ordering</pre><pre>4. Number Containers<br>   ↓<br>Forward + Reverse Index</pre><pre>5. All O`One<br>   ↓<br>Dynamic Buckets</pre><pre>6. LFU Cache<br>   ↓<br>Buckets + Ordering</pre><pre>7. Max Stack<br>   ↓<br>Multiple Independent Orderings</pre><pre>8. Stock Price<br>   ↓<br>Mutable Secondary Index</pre><pre>9. Food Ratings<br>   ↓<br>Mutable Ordered Objects</pre><h3>These 9 problems actually teach only 5 fundamental reusable ideas:</h3><ol><li><strong>Identity Lookup</strong> → HashMap&lt;ID, Object&gt;</li><li><strong>Ordering</strong> → DLL, TreeSet, TreeMap</li><li><strong>Grouping</strong> → Map&lt;Property, Collection&gt;</li><li><strong>Multiple Indexes</strong> → Same object referenced by multiple data structures.</li><li><strong>Updates</strong> → <strong>Remove → Update → Reinsert</strong> whenever an indexed property changes.</li></ol><p>These five ideas are the foundation behind most “Design a Data Structure” interview questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd240a645a7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>