<?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 Yashika Ahlawat on Medium]]></title>
        <description><![CDATA[Stories by Yashika Ahlawat on Medium]]></description>
        <link>https://medium.com/@dreamchaserdiaries?source=rss-e2ec5dbb63fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b0COGbz3RDeJq2kYUOFhVw.png</url>
            <title>Stories by Yashika Ahlawat on Medium</title>
            <link>https://medium.com/@dreamchaserdiaries?source=rss-e2ec5dbb63fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:10:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dreamchaserdiaries/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[Bringing AI to the Most Important 5 Minutes in League of Legends]]></title>
            <link>https://medium.com/@dreamchaserdiaries/bringing-ai-to-the-most-important-5-minutes-in-league-of-legends-d96f861d2ee3?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d96f861d2ee3</guid>
            <category><![CDATA[jetbrains]]></category>
            <category><![CDATA[cloud9]]></category>
            <category><![CDATA[skys-the-limit]]></category>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 18:36:18 GMT</pubDate>
            <atom:updated>2026-02-03T18:36:18.344Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How we built an intelligent draft assistant — and what it taught us about decision-making under pressure</em></p><h3>Introduction: The Game Before the Game</h3><p>In professional League of Legends, the outcome of a match is often decided before a single minion spawns.</p><p>The draft phase — those five intense minutes of champion select — is where games are won or lost. Both teams take turns banning champions they don’t want to face and picking champions they want to play. It’s a high-stakes chess match with incomplete information, time pressure, and consequences that ripple through the next 30–45 minutes of gameplay.</p><p>If you draft well, your players have tools to succeed. The right champions to counter opponents. Synergies that amplify each other. Win conditions that are achievable.</p><p>If you draft poorly? Your players are fighting uphill from minute one. Bad matchups. Awkward compositions. Win conditions that are theoretical at best.</p><p>Professional teams spend enormous resources on draft preparation. Coaches spend hours analyzing opponent tendencies, champion statistics, and meta trends. Players develop deep champion pools to give their teams flexibility. Entire practice sessions are devoted to specific compositions.</p><p>And yet, when the clock is ticking in champion select, decisions often come down to instinct, memory, and best guesses.</p><p><strong>What if AI could help?</strong></p><h3>The Chaos of Champion Select</h3><p>If you’ve never experienced professional League of Legends champion select, let me paint the picture.</p><p>The room is tense. Players sit at their computers, ready to execute whatever the coaching staff decides. The head coach stands behind them, communicating through headsets. A timer counts down — you have limited time to lock in each selection.</p><p>On screen, the draft interface shows:</p><ul><li>The champions available to pick</li><li>The champions already banned</li><li>The champions already picked by both teams</li><li>A ticking clock</li></ul><p>Now the decisions begin.</p><p><em>“They banned Maokai. What does that tell us about their plans?”</em><br><em>“Should we pick Orianna now or wait to see their mid-pick first?”</em><br><em>“If we take this champion, what does that leave them for response picks?”</em></p><p>There are over 160 champions in League of Legends. Each one has unique abilities, strengths, and weaknesses. Some champions counter others. Some synergize beautifully. Some are powerful in the current meta; others are weak.</p><p>The number of possible 10-champion draft compositions is astronomical — literally millions of unique combinations. No human being can hold all of this information in their head while also managing time pressure, reading opponents, and coordinating with their team.</p><p>Currently, teams prepare “scripts” — pre-planned draft paths that they’ve practiced and theorycrafted. But scripts can only take you so far. Every draft is different. Opponents surprise you. The meta shifts. You need to adapt in real-time.</p><p><strong>That’s where Cloud9 Draft Assistant comes in.</strong></p><h3>Introducing Cloud9 Draft Assistant</h3><p>Cloud9 Draft Assistant is an AI-powered draft companion for League of Legends that provides real-time recommendations during champion select.</p><p>It doesn’t replace coaches — it augments them. While the humans focus on reading opponents, managing team communication, and making final decisions, the AI handles:</p><ul><li>Tracking the current draft state</li><li>Recommending optimal picks and bans</li><li>Predicting what opponents might select</li><li>Calculating win probability as the draft unfolds</li><li>Explaining the reasoning behind each recommendation</li></ul><p>Think of it like a chess computer that suggests moves, explains why, and shows how each decision affects your chances of winning — except for League of Legends champion select.</p><h3>Feature Deep Dive: What Can It Do?</h3><h3>The Draft Board</h3><p>The centerpiece is the Draft Board — a visual interface that mirrors the actual champion select screen.</p><p>On the left, blue team’s bans and picks. On the right, red team’s bans and picks. In the center, a searchable grid of all available champions. At the top, the current phase indicator: BAN 1, PICK 1, BAN 2, etc.</p><p>As each selection happens in the real game, you (or an assistant) log it in the Draft Board. The interface updates instantly, showing what’s been selected and what’s still available.</p><p>But the Draft Board isn’t just for tracking — it’s actively analyzing.</p><h3>AI Recommendations</h3><p>For each phase of the draft, the AI provides recommendations.</p><p>Let’s say it’s Blue Team’s first pick. The AI might recommend:</p><p><strong>Recommended: Maokai</strong><br><em>Confidence: High</em><br><em>Reasoning: “Maokai is the top priority support in the current meta with an 54% professional win rate. Based on opponent tendencies, they’re likely to pick Nautilus if Maokai is available — Maokai is stronger in head-to-head matchups. Additionally, Maokai’s crowd control synergizes well with later pick options like Orianna or Jinx.”</em></p><p><strong>Alternative: K’Sante</strong><br><em>Confidence: Medium</em><br><em>Reasoning: “K’Sante is a flex pick that can go top or mid, hiding your strategy. Taking K’Sante early keeps more options open for later phases.”</em></p><p><strong>Alternative: Nautilus</strong><br><em>Confidence: Medium</em><br><em>Reasoning: “If you’re confident Maokai will be banned by the opponent, Nautilus is a comparable option with strong engage.”</em></p><p>The AI doesn’t just say “pick this champion.” It explains <em>why</em> — considering synergy, counterplay, meta strength, and opponent tendencies. Coaches can take the recommendation at face value or use the reasoning to inform their own decision.</p><h3>Win Probability Meter</h3><p>Throughout the draft, a win probability meter displays the current estimated chance of victory for each team.</p><p>The draft starts at 50/50. As selections happen, the probability shifts:</p><p><em>Blue picks Maokai: 52% Blue — 48% Red</em><br><em>Red picks Nautilus: 51% Blue — 49% Red</em><br><em>Blue picks Orianna: 53% Blue — 47% Red</em><br><em>Red picks Yone: 54% Blue — 46% Red</em></p><p>Players and coaches can watch the probability update in real-time, understanding how each decision affects their chances. Did that pick help or hurt? How much? The meter provides instant feedback.</p><p>This is powerful for learning. After the match, teams can review the draft and see exactly when their probability spiked or dipped. “That’s when we made a mistake” becomes obvious.</p><h3>Opponent Predictions</h3><p>One of the hardest parts of the draft is anticipating what the opponent will do.</p><p>Based on historical data from GRID’s professional match database, the AI predicts likely opponent selections:</p><p><em>“Based on their draft tendencies, the opponent’s likely next pick is:</em></p><ul><li><em>Kai’Sa (45% probability) — their ADC has 80% pick rate on this champion</em></li><li><em>Varus (30% probability) — fits their current composition</em></li><li><em>Ezreal (15% probability) — safe fallback option”</em></li></ul><p>This information is invaluable. If you know the opponent is likely to pick Kai’Sa, you can prepare a counter — either banning her or picking a champion that matches well against her.</p><p>Prediction isn’t perfect — opponents sometimes surprise you — but having a data-driven estimate is far better than pure guesswork.</p><h3>Draft Simulation</h3><p>What if you want to practice drafts without the pressure of a real match?</p><p>Draft Simulation mode lets you run practice drafts against an AI opponent. You pick for one team; the AI responds intelligently for the other.</p><p>This is useful for:</p><ul><li>Testing new strategies before using them in competition</li><li>Exploring how different draft paths feel</li><li>Training new players or coaches on draft principles</li><li>Preparing for specific opponent tendencies</li></ul><p>The AI opponent isn’t perfect — it won’t perfectly replicate any specific team — but it provides reasonable resistance that makes practice meaningful.</p><h3>Meta Analysis</h3><p>The meta in League of Legends shifts constantly. Patches change champion power levels. Professional play discovers new strategies. What was weak last month might be dominant today.</p><p>The Meta Champions feature provides a current tier list based on recent professional play data:</p><p><strong>S-Tier (Always Pick/Ban):</strong></p><ul><li>Maokai (62% pick/ban rate, 54% win rate)</li><li>K’Sante (85% pick/ban rate, 52% win rate)</li><li>Orianna (58% pick/ban rate, 51% win rate)</li></ul><p><strong>A-Tier (Strong Options):</strong></p><ul><li>Nautilus, Rell, Jinx, Xayah, Azir…</li></ul><p><strong>B-Tier (Situational):</strong></p><ul><li>…and so on</li></ul><p>This keeps teams informed about the current meta without requiring hours of research. When the patch changes and the meta shifts, the data updates accordingly.</p><h3>Real Scenario: How It Works in Practice</h3><p>Let’s walk through a realistic draft scenario to see how Cloud9 Draft Assistant adds value.</p><p><strong>The Setup:</strong> Your team (Blue side) is facing a strong opponent in a playoff match. You’ve prepared several strategies but need to adapt based on what the opponent shows.</p><p><strong>Ban Phase 1:</strong></p><p>You ban Maokai — a power pick you don’t want to face. Opponent bans K’Sante. You ban Yone — their mid-laner’s signature champion. Opponent bans Jinx.</p><p>The AI notes: <em>“Opponent banning Jinx but not their own strong ADC targets suggests they plan to play around ADC. Consider prioritizing bot pressure.”</em></p><p><strong>Pick Phase 1:</strong></p><p>It’s your first pick. The AI recommends Nautilus:</p><p><em>“With Maokai banned, Nautilus is the next-best support option. Taking it denies the opponent their likely support plan while giving you strong engage. Win probability increases to 52% if selected.”</em></p><p>You pick Nautilus.</p><p>Opponent picks Viego and Xayah. A jungle-ADC core that signals their composition direction.</p><p>The AI updates: <em>“Opponent showing AD-heavy composition. Consider AP mid and tank top to balance damage profiles. Their Viego is vulnerable to crowd control chains.”</em></p><p><strong>Pick Phase 2:</strong></p><p>Your turn for two picks. The AI recommends:</p><ol><li><em>Orianna (mid)</em> — “Strong control mage with CC that chains well with Nautilus. Good matchup into likely opponent mid picks.”</li><li><em>Sejuani (jungle)</em> — “Another CC threat that synergizes with your composition. Makes Viego’s life difficult.”</li></ol><p>You lock in Orianna and Sejuani.</p><p>Win probability: 55% Blue.</p><p><strong>And so on…</strong></p><p>Throughout the draft, the AI provides continuous guidance. Not making decisions for you — but ensuring you have the best possible information to make your own decisions.</p><h3>The Philosophy: Augmentation, Not Replacement</h3><p>A common fear with AI in any competitive domain is that it will replace human judgment. Coaches might worry: “If the AI is making recommendations, why do you need me?”</p><p>This concern misses how the tool is designed.</p><p>Cloud9 Draft Assistant augments coaches. It handles the computational complexity — tracking champion relationships, calculating probabilities, analyzing opponent data — so coaches can focus on what humans do best:</p><ul><li><strong>Reading the room.</strong> Is our star player confident on this champion? Is the opponent’s coach showing nervousness?</li><li><strong>Managing egos.</strong> Sometimes the “optimal” pick isn’t the right pick because of team dynamics.</li><li><strong>Long-term thinking.</strong> Do we want to reveal this strategy now, or save it for a more important match?</li><li><strong>Intuition.</strong> Sometimes experienced coaches have a gut feeling that defies the data — and they’re often right.</li></ul><p>The AI provides information. Humans provide wisdom. Together, they make better decisions than either could alone.</p><h3>The Data Behind the Recommendations</h3><p>You might wonder: where do these recommendations come from? How does the AI “know” what to suggest?</p><p>The answer is data — specifically, professional match data from GRID.</p><p>We analyze thousands of professional League of Legends games to understand:</p><p><strong>Champion Performance:</strong> Raw statistics on win rates, pick rates, ban rates, and performance metrics across different skill levels and regions.</p><p><strong>Synergies:</strong> Which champion combinations perform better than expected when played together. Orianna + Gnar, for example, have a famous synergy around combined ultimate abilities.</p><p><strong>Counters:</strong> Which champions perform well against which other champions. Some matchups are so lopsided that picking into them is a significant mistake.</p><p><strong>Opponent Tendencies:</strong> How specific teams and players behave in draft. Some players have very narrow champion pools; others are flexible. Some teams always prioritize certain strategies.</p><p>All of this data flows into the recommendation engine, which synthesizes it in real-time during the draft.</p><h3>Lessons from Building the Draft Assistant</h3><p>Creating Cloud9 Draft Assistant taught us about competitive gaming, AI, and the nature of good decision support.</p><h3>Lesson 1: League of Legends Draft Is Incredibly Complex</h3><p>When we started, we underestimated how complex champion select really is. 160+ champions. Role assignments. Synergies. Counters. Meta shifts. Opponent habits. Team preferences. Player champion pools. Flex picks that hide information.</p><p>Building a system that could reason about all of this required serious effort. We have new respect for professional coaches who manage this complexity without AI assistance.</p><h3>Lesson 2: Explanation Matters as Much as Recommendation</h3><p>Early versions of the tool just said: “Pick Orianna.” Users hated it. They didn’t trust recommendations they couldn’t understand.</p><p>When we added explanations — “Pick Orianna because she synergizes with Nautilus and counters likely enemy mid picks” — trust increased dramatically. Users felt like they were getting useful information, not mysterious commands.</p><p>This is a general lesson for AI tools. Transparency builds trust.</p><h3>Lesson 3: Speed Is Non-Negotiable</h3><p>In champion select, you have limited time for each decision. An AI that takes 30 seconds to generate a recommendation is useless — the clock has already moved on.</p><p>We optimized aggressively for speed. Recommendations appear in under a second. The trade-off was sometimes accepting slightly less comprehensive analysis, but the speed was worth it.</p><h3>What’s Next for Draft?</h3><p>We’re excited about future development:</p><p><strong>Live Integration with Professional Broadcasts:</strong> Imagine watching a professional match and seeing AI recommendations in real-time, just like the teams might see. Great for fans who want to understand draft strategy.</p><p><strong>Team-Specific Training:</strong> Custom AI models trained on your specific team’s data, understanding your player pools and strategic preferences.</p><p><strong>Voice Interface:</strong> Hands-free operation so coaches can receive recommendations without looking at screens.</p><p><strong>Post-Draft Analysis:</strong> Detailed breakdowns after the draft showing key decision points and what alternatives existed.</p><h3>Why This Matters: The Democratization of Intelligence</h3><p>The best esports organizations have analytics departments. They have coaches with decades of experience. They have resources to spend on preparation.</p><p>Smaller teams don’t have those advantages. They’re competing with fewer resources, less experience, and less information.</p><p>AI tools like Cloud9 Draft Assistant level the playing field. The analytical power that used to require a dedicated analyst is now available to everyone. The pattern recognition that used to require years of experience is now embedded in software.</p><p>This democratization is good for esports. More competitive matches. More upsets. More storylines. The dominance of resource-rich organizations becomes less assured when everyone has access to intelligent tools.</p><h3>Conclusion: Drafting Smarter</h3><p>The draft phase will always be a human endeavor. The decisions, the pressure, the moments of insight — these are what make champion select exciting.</p><p>But humans don’t have to do it alone.</p><p>Cloud9 Draft Assistant provides the information backbone that enables better decisions. Track the draft state. Get recommendations with explanations. Watch win probability shift. Predict opponent moves.</p><p>The game within the game just got more intelligent.</p><p><em>Built for the Cloud9 x GRID Hackathon. We’d love to hear your thoughts!</em></p><p><strong>Try It Yourself:</strong></p><ul><li>Live Demo: c9-draft-ui.vercel.app</li><li>API Documentation: c9-draft-api.onrender.com/docs</li><li>GitHub: github.com/AvishKaushik/c9-draft-ui</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d96f861d2ee3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[847. Shortest Path Visiting All Nodes]]></title>
            <link>https://medium.com/@dreamchaserdiaries/847-shortest-path-visiting-all-nodes-d7edf99b591e?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7edf99b591e</guid>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 16:06:19 GMT</pubDate>
            <atom:updated>2025-08-16T16:06:19.530Z</atom:updated>
            <content:encoded><![CDATA[<p>Today we will be solving leetcode hard question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNyYTPZ0ZpxeqWzDHLAnUA.png" /><figcaption>Question Image</figcaption></figure><p>As soon as I read the question, the first keywords that stuck out to me was “<strong>Shortest Path”</strong> and “<strong>nodes/graph</strong>” which immediately led to me think about BFS. The main issue was the line — <strong>You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges </strong>because in normal BFS, we can just visit a node once and we mark it as visited. Also if we are allowed to visit multiple nodes, what about this situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*Tp_VPhH-BKJxkXV89YSQeg.png" /><figcaption>Counter Example.</figcaption></figure><h3><strong>Problem — 1</strong></h3><p>If I am allowed to visit a node multiple times, what if I go from. 0 -&gt;1 -&gt;0 -&gt;1 -&gt;0 and so on. How can I prevent this deadlock. This led to me think that we need to adjust our visited state a bit. Question is how?</p><p>What if in visited set, I store the current node and the previous nodes which I have taken to reach this current node? Would it help me to remove this deadlock condition?</p><p>Let’s check it out.</p><p>Let’s assume I will follow that path 0 -&gt; 1 -&gt; 0 -&gt; 1. I am standing at first 0 node. In visited set I will insert {0, {0}}. I go to the next 1, in visited I will insert {1, {0,1}}. Go back to 0, in visited I would have stored {0, {0,1}} but wait I have already processed this state. Hence I don’t need to do this again!</p><p>Next question is how do I store visited nodes efficiently. Look at the given constraints of the question-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*3jdPBLWlxCElxseNZEKipw.png" /><figcaption>Constraints</figcaption></figure><p>The number of nodes is small hence I can use bit masking to store the nodes that I have seen so far.</p><h3><strong>Problem — 2</strong></h3><p>From where to start the BFS? In the given example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*Tp_VPhH-BKJxkXV89YSQeg.png" /><figcaption>Given example</figcaption></figure><p>If i start BFS from 0, my path would be. 0 -&gt; 1 -&gt; 0 -&gt; 2 -&gt;0 -&gt;3 == 5 but the optimal answer is 1 -&gt; 0 -&gt; 2 -&gt;0 -≥= 4. Hence we need to start BFS from every node and the moment where we have visited all the nodes would be our answer!</p><h3><strong>Bringing everything together(DRY RUN!)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*Tp_VPhH-BKJxkXV89YSQeg.png" /><figcaption>Dry run question.</figcaption></figure><p>Since we will be starting BFS from every node, in queue we will be adding all the staring nodes with their respective masks.</p><pre>graph = [[1,2,3],[0],[0],[0]]<br>n = 4<br>allVisited = 1111b = 15<br>state = (node, mask)</pre><h3>Level 0 (initial queue, steps = 0)</h3><p><strong>Queue (front → back)</strong><br> [(0,0001), (1,0010), (2,0100), (3,1000)]</p><p><strong>Visited (set of states)</strong><br> { (0,0001), (1,0010), (2,0100), (3,1000) }</p><p><strong>Process this level → enqueue unseen neighbors</strong></p><ul><li>From (0,0001) → (1,0011), (2,0101), (3,1001)</li><li>From (1,0010) → (0,0011)</li><li>From (2,0100) → (0,0101)</li><li>From (3,1000) → (0,1001)</li></ul><p><strong>Queue for next level</strong><br> [(1,0011), (2,0101), (3,1001), (0,0011), (0,0101), (0,1001)]</p><p><strong>Visited added this level</strong><br> { (1,0011), (2,0101), (3,1001), (0,0011), (0,0101), (0,1001) }</p><p>steps = 1</p><h3>Level 1 (steps = 1)</h3><p><strong>Queue (size 6)</strong><br> [(1,0011), (2,0101), (3,1001), (0,0011), (0,0101), (0,1001)]</p><p><strong>Process</strong></p><ul><li>(1,0011) → (0,0011) (already seen)</li><li>(2,0101) → (0,0101) (seen)</li><li>(3,1001) → (0,1001) (seen)</li><li>(0,0011) → (1,0011) (seen) , (2,0111) <strong>NEW , </strong>(3,1011) <strong>NEW</strong></li><li>(0,0101) → (1,0111) <strong>NEW, </strong>(2,0101) (seen), (3,1101) <strong>NEW</strong></li><li>(0,1001) → (1,1011) <strong>NEW, </strong>(2,1101) <strong>NEW, </strong>(3,1001) (seen)</li></ul><p><strong>Queue for next level</strong><br> [(2,0111), (3,1011), (1,0111), (3,1101), (1,1011), (2,1101)]</p><p><strong>Visited added this level</strong><br> { (2,0111), (3,1011), (1,0111), (3,1101), (1,1011), (2,1101) }</p><p>steps = 2</p><h3>Level 2 (steps = 2)</h3><p><strong>Queue (size 6)</strong><br> [(2,0111), (3,1011), (1,0111), (3,1101), (1,1011), (2,1101)]</p><p><strong>Process</strong></p><ul><li>(2,0111) → (0,0111) <strong>NEW</strong></li><li>(3,1011) → (0,1011) <strong>NEW</strong></li><li>(1,0111) → (0,0111) (dup)</li><li>(3,1101) → (0,1101) <strong>NEW</strong></li><li>(1,1011) → (0,1011) (dup)</li><li>(2,1101) → (0,1101) (dup)</li></ul><p><strong>Queue for next level</strong><br> [(0,0111), (0,1011), (0,1101)]</p><p><strong>Visited added this level</strong><br> { (0,0111), (0,1011), (0,1101) }</p><p>steps = 3</p><h3>Level 3 (steps = 3)</h3><p><strong>Queue (size 3)</strong><br> [(0,0111), (0,1011), (0,1101)]</p><p><strong>Process</strong></p><ul><li>(0,0111) → (1,0111) (seen), (2,0111) (seen), (3,1111) <strong>NEW</strong> ← all nodes visited mask</li><li>(0,1011) → (1,1011) (seen), (2,1111) <strong>NEW, </strong>(3,1011) (seen)</li><li>(0,1101) → (1,1111) <strong>NEW, </strong>(2,1101) (seen), (3,1101) (seen)</li></ul><p><strong>Queue for next level</strong><br> [(3,1111), (2,1111), (1,1111)]</p><p><strong>Visited added this level</strong><br> { (3,1111), (2,1111), (1,1111) }</p><p>steps = 4</p><h3>Level 4 (steps = 4)</h3><p>Pop first state (3,1111).<br> mask == allVisited → <strong>return </strong><strong>steps = 4.</strong></p><p><strong>Answer:</strong> the shortest path that visits all nodes is <strong>4</strong>.</p><h3><strong>Code</strong></h3><pre>class Solution {<br>public:<br>    int shortestPathLength(vector&lt;vector&lt;int&gt;&gt;&amp; graph) {<br>        int n = graph.size();<br>        if (n &lt;= 1) return 0;<br><br>        int totalDistance = 0;<br>        queue&lt;pair&lt;int,int&gt;&gt;q; // node and mask<br>        set&lt;pair&lt;int,int&gt;&gt; vis; // node and path mask<br><br>        for(int i=0;i&lt;n;i++){<br>            int mask = 1&lt;&lt;i;<br>            q.push({i,mask});<br>            vis.insert({i,mask});<br>        }<br><br>        int allVisited = (1 &lt;&lt; n) - 1;<br><br>        while(!q.empty()){<br>            int size = q.size();<br>            for(int i = 0;i&lt;size;i++){<br>                int currentNode = q.front().first;<br>                int currentMask = q.front().second;<br>                q.pop();<br><br>                if(currentMask == allVisited){<br>                    return totalDistance;<br>                }<br>                for(auto it : graph[currentNode]){<br>                    int newMask = currentMask | (1 &lt;&lt; it);<br>                    if (vis.find({it, newMask}) == vis.end()){<br>                        vis.insert({it, newMask});<br>                        q.push({it, newMask});<br>                    }<br>                }<br>            }<br>            // distance is at current level<br>            totalDistance++;<br>        }<br>        return totalDistance;<br>    }<br>};</pre><h3>Key Takeaways (Beginner Friendly)</h3><ul><li><strong>Parallel BFS trick</strong>: If you want to run BFS starting from <em>any</em> node, just push <strong>all nodes</strong> into the queue at the beginning. Then process them level by level in parallel.</li><li><strong>State matters</strong>: In problems where revisiting is allowed, track not just the node but also the <strong>set of visited nodes</strong> → (node, visitedMask).</li><li><strong>Bitmasking is your friend</strong>: For small graphs, bitmasking is an efficient way to represent “which nodes have been visited.”</li><li><strong>Stop condition</strong>: The first time your visited mask equals “all nodes visited,” you’ve found the shortest path.</li></ul><p>This problem looks intimidating at first, but once you realize BFS can be extended with state and bitmasking, it falls into place. It’s a classic example of how <em>“BFS + bitmask = powerful template”</em> for graph problems involving visiting all nodes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7edf99b591e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1235. Maximum Profit in Job Scheduling — Leetcode Hard]]></title>
            <link>https://medium.com/@dreamchaserdiaries/1235-maximum-profit-in-job-scheduling-leetcode-hard-becada8d8ba0?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/becada8d8ba0</guid>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 05:52:58 GMT</pubDate>
            <atom:updated>2025-06-13T05:52:58.494Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://leetcode.com/problems/maximum-profit-in-job-scheduling/">1235. Maximum Profit in Job Scheduling</a> — Leetcode Hard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64DiphgRFlKzv1mVj7v_xw.png" /><figcaption>Question Statement</figcaption></figure><p>You’re given <strong>n jobs</strong>, each with:</p><ul><li>a <strong>start time</strong></li><li>an <strong>end time</strong></li><li>and a <strong>profit</strong> you’ll earn by completing it.</li></ul><p>You want to select a <strong>subset of non-overlapping jobs</strong> (i.e., no two selected jobs should be active at the same time).</p><p>Note: If one job ends at time X, you&#39;re <strong>allowed</strong> to start another job <strong>starting exactly at time </strong><strong>X</strong>.</p><p>Your goal is to pick jobs in such a way that the <strong>total profit is maximized</strong>.</p><p>Return that <strong>maximum profit</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MY1avieks22SyCNxQpjwA.png" /></figure><h3>Pattern Trigger: What Clues Does the Problem Give?</h3><p>When I first read this problem, a few things jumped out at me:</p><ol><li><strong>“Maximize profit”</strong> — The goal is to maximize profit — which hints at dynamic programming or greedy approaches. But since greedy fails here (locally optimal choices may block better future ones), we lean toward recursion + memoization.</li><li><strong>“No two jobs should overlap”</strong> — this immediately reminds me of the <strong>Weighted Interval Scheduling</strong> problem, which is usually solved using <strong>binary search + DP</strong>.</li><li><strong>Jobs have [start, end] windows and a profit</strong> — that points to an optimal substructure: Either take the current job and skip overlapping ones, Or skip this job and try others.(Choices + decisions)</li></ol><h3>🎯 So, what’s the approach?</h3><p>You think:</p><blockquote><em>“Can I sort jobs? And for each job, find the next non-overlapping one?”</em></blockquote><p>That’s where <strong>Greedy fails</strong> (because taking the job with max profit now may block better ones later), and <strong>Recursion + Memoization</strong> comes in:</p><p>You’ll need:</p><ul><li>A way to <strong>choose a job or skip it</strong></li><li>A way to <strong>quickly find the next compatible job.</strong></li><li>A <strong>dp cache</strong> to store results for overlapping subproblems.</li></ul><p>So, what we want is that at a particular index, we can choose to do a job or nota and return the max of both options. If we choose to do the job, we have to find the next valid one.</p><p>How to sort the job based on their start time.</p><pre>int n = startTime.size();<br>vector&lt;tuple&lt;int, int, int&gt;&gt; jobs;<br>for(int i = 0; i &lt; n; i++) {<br>    jobs.push_back({startTime[i], endTime[i], profit[i]});<br>}<br><br>// Sort jobs by start time (or end time would also work)<br>sort(jobs.begin(), jobs.end());<br><br>for(int i = 0; i &lt; n; i++) {<br>    tie(startTime[i], endTime[i], profit[i]) = jobs[i];<br>}</pre><p><strong>The work of tie() is to unpack the tuple values into separate variables. Bacially separating back the start time, end time and the profit.</strong></p><p>We call our recursive helper function starting from index 0.</p><pre>util(startTime,endTime,profit,0);</pre><p>At a particular index, we have two options — either do that job or don’t do that job. First we will explore dontDo. If we are not doing the job, we simply move onto the next index and don’t add anything in the profit.</p><pre>// don&#39;t do the job<br>int dontDo= util(startTime,endTime,profit,index+1);</pre><p>If we do the job, we add the profit, we find the next job where the start time[newJob]≥ endTime[currentJob]. Let’s call the index of that job, nextIndex.</p><pre>int doJob = profit[index] + util(startTime, endTime, profit, nextIndex);<br>return max(dontDo,doJob);</pre><pre>// Base condition<br>if(index &gt;= profit.size()) {<br>    return 0;<br>}</pre><h3>How to find the nextIndex??</h3><p>Either we run a for loop from the currentIndex to the end and find the first index where startTime[newJob]≥ endTime[index].</p><pre>// get the next jobs to be done and return the max profit from there.<br>int nextIndex = index + 1;<br>while(nextIndex &lt; profit.size() &amp;&amp; startTime[nextIndex] &lt; endTime[index]) {<br>    nextIndex++;<br>}</pre><p>But the time complexity for this can be O(n). And for each index, we will be finding the nextIndex, it would be extremely expensive.</p><p>Question is how to find the next index in an optimal way?</p><p><strong>Some key words - searching, Sorted array -&gt; Immediately you should think of Binary search.</strong></p><p>In C++, the <strong>std::lower_bound()</strong> is a built-in function used to find the position of an element in a sorted range that has a value not less than the given value.</p><h3>Syntax of lower_bound()</h3><blockquote><strong>std::lower_bound </strong>(first, last, val, comp);</blockquote><pre>int nextIndex = lower_bound(startTime.begin(), startTime.end(), endTime[index]) — startTime.begin();</pre><p>lower_bound(startTime.begin(), startTime.end(), endTime[index]) gives us an <strong>iterator</strong> to the first job where:</p><pre>startTime[i] &gt;= endTime[index]</pre><p>and we substract startTime.begin() to get the index from the iterator.</p><p>Hence the code becomes.</p><pre>class Solution {<br>public:<br>    int util(vector&lt;int&gt;&amp; startTime, vector&lt;int&gt;&amp; endTime, vector&lt;int&gt;&amp; profit, int index){<br>        if(index &gt;= profit.size()) {<br>            return 0;<br>        }<br>        // get the next jobs to be done and return the max profit from there.<br>        int nextIndex = lower_bound(startTime.begin(), startTime.end(), endTime[index]) - startTime.begin();<br><br>        // Option 1: take the current job<br>        int doJob = profit[index] + util(startTime, endTime, profit, nextIndex);<br>        // don&#39;t do the job<br>        int dontDo= util(startTime,endTime,profit,index+1);<br>        return max(doJob,dontDo);<br>    }<br>    int jobScheduling(vector&lt;int&gt;&amp; startTime, vector&lt;int&gt;&amp; endTime, vector&lt;int&gt;&amp; profit) {<br>        int n = startTime.size();<br>        vector&lt;tuple&lt;int, int, int&gt;&gt; jobs;<br>        for(int i = 0; i &lt; n; i++) {<br>            jobs.push_back({startTime[i], endTime[i], profit[i]});<br>        }<br><br>        // Sort jobs by start time (or end time would also work)<br>        sort(jobs.begin(), jobs.end());<br><br>        for(int i = 0; i &lt; n; i++) {<br>            tie(startTime[i], endTime[i], profit[i]) = jobs[i];<br>        }<br>        return util(startTime,endTime,profit,0);<br>    }<br>};</pre><h3>Time complexity without memoization</h3><p>T(n) = O(2^n × log n)<br>2^n → number of recursion paths (like a full binary tree)log n → cost per call for the lower_bound (binary search).</p><h3>Code with Memoization</h3><pre>class Solution {<br>public:<br>    int util(vector&lt;int&gt;&amp; startTime, vector&lt;int&gt;&amp; endTime, vector&lt;int&gt;&amp; profit, int index, vector&lt;int&gt;&amp;dp){<br>        if(index &gt;= profit.size()) {<br>            return 0;<br>        }<br>        // get the next jobs to be done and return the max profit from there.<br>        int nextIndex = lower_bound(startTime.begin(), startTime.end(), endTime[index]) - startTime.begin();<br>        if(dp[index]!=-1){<br>            return dp[index];<br>        }<br><br>        // Option 1: take the current job<br>        int doJob = profit[index] + util(startTime, endTime, profit, nextIndex,dp);<br>        // don&#39;t do the job<br>        int dontDo= util(startTime,endTime,profit,index+1,dp);<br>        return dp[index]= max(doJob,dontDo);<br>    }<br>    int jobScheduling(vector&lt;int&gt;&amp; startTime, vector&lt;int&gt;&amp; endTime, vector&lt;int&gt;&amp; profit) {<br>        int n = startTime.size();<br>        vector&lt;tuple&lt;int, int, int&gt;&gt; jobs;<br>        for(int i = 0; i &lt; n; i++) {<br>            jobs.push_back({startTime[i], endTime[i], profit[i]});<br>        }<br><br>        // Sort jobs by start time (or end time would also work)<br>        sort(jobs.begin(), jobs.end());<br><br>        for(int i = 0; i &lt; n; i++) {<br>            tie(startTime[i], endTime[i], profit[i]) = jobs[i];<br>        }<br>        vector&lt;int&gt;dp(startTime.size()+1,-1);<br>        return util(startTime,endTime,profit,0,dp);<br>    }<br>};</pre><h3>Time Complexity with memoization</h3><p>O(n × log n)<br>n = number of jobs (dp entries)log n = cost to find next compatible job using binary search</p><h3>**Key Takeaways**</h3><p>- When you see “maximize profit with constraints,” think of dynamic programming.<br>- Sorting + Binary Search helps efficiently find the next non-overlapping option.<br>- Recursion is a great way to model decisions first — then memoize to optimize.<br>- Problems like this are variations of the classic Weighted Interval Scheduling.</p><p>This problem beautifully blends classic DP thinking with modern coding techniques like `lower_bound()` and `tie()`.</p><p>Happy Coding 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=becada8d8ba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[301. Remove Invalid Parenthesesc — Leetcode Hard]]></title>
            <link>https://medium.com/@dreamchaserdiaries/301-remove-invalid-parenthesesc-leetcode-hard-d3cbbd05ef34?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3cbbd05ef34</guid>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 08:05:32 GMT</pubDate>
            <atom:updated>2025-06-11T08:06:15.716Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://leetcode.com/problems/remove-invalid-parentheses/">301. Remove Invalid Parentheses</a>— Leetcode Hard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybdSPpr2CUOoWgAwynrxrw.png" /><figcaption>Question Description</figcaption></figure><p>Today we will be solving Remove Invalid Parentheses — Leetcode — 301. The question states that — You’re given a string s made up of letters and parentheses ( and ). Your task is to remove the <strong>fewest number of parentheses</strong> necessary to make the string <strong>valid</strong> — where valid means all opening and closing parentheses are properly matched.</p><p>Return <strong>all possible unique valid strings</strong> you can form after the <strong>minimum number of removals</strong>. The order of the results does not matter.</p><h3>Pattern Trigger</h3><blockquote><em>💡 Whenever a problem asks us to </em><strong><em>generate all valid combinations</em></strong><em>, or </em><strong><em>explore all possible ways to make a string valid</em></strong><em>, that’s a strong signal to reach for </em><strong><em>recursion or backtracking.</em></strong></blockquote><h3>Counting the number of removals</h3><p>The first step is to determine how many opening ( and closing ) parentheses we need to remove. To do this, we’ll use two counters: leftRemove and rightRemove. These will track the number of unmatched parentheses that need to be removed.</p><p>We iterate through the string character by character:</p><ul><li>When we see a &#39;(&#39;, we increment leftRemove since it might not have a matching &#39;)&#39;.</li><li>When we see a &#39;)&#39;, we check if there’s an unmatched &#39;(&#39; (i.e., leftRemove &gt; 0). If so, we pair it by decrementing leftRemove. Otherwise, it means this &#39;)&#39; has no match, so we increment rightRemove.</li></ul><p>By the end of this loop, leftRemove and rightRemove will tell us the exact number of unmatched opening and closing parentheses we need to remove.</p><pre>int leftRemove = 0, rightRemove = 0;<br>        for(char c : s){<br>            if(c==&#39;(&#39;){<br>               leftRemove++; <br>            }<br>            else if(c ==&#39;)&#39;){<br>                if(leftRemove&gt;0){<br>                    leftRemove--; <br>                } <br>                else{<br>                    rightRemove++;<br>                }<br>            }<br>        }</pre><h3>Recursion + Memoization</h3><p>Once you have this information, we can do a recursion on the given string to find all the valid patterns. We will be using a visited set to avoid the processing of same strings. Imagine the string:</p><pre>s = &quot;()())()&quot;</pre><p>Now let’s say we try removing a ) at index 3 or 4 — both result in the same string. To avoid processing duplicates, we use a visited set.</p><pre>→ &quot;()()()&quot;<br>→ &quot;()()()&quot;</pre><p>Without a visited set:</p><ul><li>You’ll recurse again on &quot;())()()&quot; <strong>multiple times</strong>, doing redundant work</li><li>The recursion tree grows exponentially</li><li>You hit <strong>TLE (Time Limit Exceeded)</strong> on longer inputs. Visited is Memoization!!</li></ul><pre>unordered_set&lt;string&gt; visited;// kinda like dfs<br>visited.insert(s);<br>// string,index,leftRemove,rightRemove<br>dfs(s, 0, leftRemove, rightRemove, visited);</pre><p>Now onto the dfs function. To get all the combination, we have to try to remove from every valid position.</p><pre>void dfs(string s, int index, int leftRemove, int rightRemove, unordered_set&lt;string&gt;&amp; visited) {<br><br>        for (int i = index; i &lt; s.size(); ++i) {<br>            // Skip duplicate removals<br>            if (i &gt; index &amp;&amp; s[i] == s[i - 1]) continue;<br><br>            // Only try to remove parentheses<br>            if (s[i] == &#39;(&#39; || s[i] == &#39;)&#39;) {<br>                if (s[i] == &#39;(&#39; &amp;&amp; leftRemove &gt; 0) {<br>                    string temp = s;<br>                    temp.erase(i, 1);<br>                    if (visited.count(temp) == 0) {<br>                        visited.insert(temp);<br>                        dfs(temp, i, leftRemove - 1, rightRemove, visited);<br>                    }<br>                } else if (s[i] == &#39;)&#39; &amp;&amp; rightRemove &gt; 0) {<br>                      string temp = s;<br>                      temp.erase(i, 1);<br>                    if (visited.count(temp) == 0) {<br>                        visited.insert(temp);<br>                        dfs(temp, i, leftRemove, rightRemove - 1, visited);<br>                    }<br>                }<br>            }<br>        }<br><br>}</pre><h3>Special note on this condition- if (i &gt; index &amp;&amp; s[i] == s[i — 1]) continue;</h3><p>This line helps us avoid making the <strong>same removal decision multiple times</strong> for <strong>identical consecutive characters</strong>.</p><p>For example, take the string s = &quot;((()&quot;.<br> If you try removing a &#39;(&#39; at index 0, 1, or 2, you&#39;ll end up with the <strong>same resulting string</strong>: &quot;(()&quot;.</p><p>So instead of exploring all three redundant options, we only remove the <strong>first </strong><strong>&#39;(&#39;</strong> in the sequence and <strong>skip the rest</strong>, which makes the recursion more efficient and avoids duplicate results.</p><h3>Base Condition</h3><p>Final step of recursion in base condition which in our case would be -</p><pre>if (leftRemove == 0 &amp;&amp; rightRemove == 0) {<br>    if (isValid(s)) {<br>        result.insert(s);<br>    }<br>    return;<br>}</pre><p>isValid function is checking if the string that we formed is valid or not, which is going to be very similar to the way where we were checking leftRemove and rightRemove.</p><pre>bool isValid(const string&amp; s) {<br>        int count = 0;<br>        for (char c : s) {<br>            if (c == &#39;(&#39;) count++;<br>            else if (c == &#39;)&#39;) {<br>                if (count == 0) return false;<br>                count--;<br>            }<br>        }<br>        return count == 0;<br>    }</pre><h3>Full code</h3><pre>class Solution {<br>public:<br>    unordered_set&lt;string&gt; result;<br>    bool isValid(const string&amp; s) {<br>        int count = 0;<br>        for (char c : s) {<br>            if (c == &#39;(&#39;) count++;<br>            else if (c == &#39;)&#39;) {<br>                if (count == 0) return false;<br>                count--;<br>            }<br>        }<br>        return count == 0;<br>    }<br>    void dfs(string s, int index, int leftRemove, int rightRemove, unordered_set&lt;string&gt;&amp; visited) {<br>        if (leftRemove == 0 &amp;&amp; rightRemove == 0) {<br>            if (isValid(s)) {<br>                result.insert(s);<br>            }<br>            return;<br>        }<br>        for (int i = index; i &lt; s.size(); ++i) {<br>            // Skip duplicate removals<br>            if (i &gt; index &amp;&amp; s[i] == s[i - 1]) continue;<br><br>            // Only try to remove parentheses<br>            if (s[i] == &#39;(&#39; || s[i] == &#39;)&#39;) {<br>                string temp = s;<br>                temp.erase(i, 1);<br><br>                if (s[i] == &#39;(&#39; &amp;&amp; leftRemove &gt; 0) {<br>                    if (visited.count(temp) == 0) {<br>                        visited.insert(temp);<br>                        dfs(temp, i, leftRemove - 1, rightRemove, visited);<br>                    }<br>                } else if (s[i] == &#39;)&#39; &amp;&amp; rightRemove &gt; 0) {<br>                    if (visited.count(temp) == 0) {<br>                        visited.insert(temp);<br>                        dfs(temp, i, leftRemove, rightRemove - 1, visited);<br>                    }<br>                }<br>            }<br>        }<br>    }<br>    vector&lt;string&gt; removeInvalidParentheses(string s) {<br>        int leftRemove = 0, rightRemove = 0;<br>        for(char c : s){<br>            if(c==&#39;(&#39;){<br>               leftRemove++; <br>            }<br>            else if(c ==&#39;)&#39;){<br>                if(leftRemove&gt;0){<br>                    leftRemove--; <br>                } <br>                else{<br>                    rightRemove++;<br>                }<br>            }<br>        }<br>        unordered_set&lt;string&gt; visited;// Memoization<br>        visited.insert(s);<br>        dfs(s, 0, leftRemove, rightRemove, visited);<br><br>        if (result.empty()) return {&quot;&quot;};<br>        return vector&lt;string&gt;(result.begin(), result.end());<br>    }<br>};</pre><h3>🏁 Wrapping Up</h3><p>The <strong>“Remove Invalid Parentheses”</strong> problem is a classic example of how recursion, backtracking, and smart pruning can work together to solve a seemingly brute-force problem efficiently.</p><p>By first calculating the minimum number of ( and ) to remove, and then using recursive DFS to explore all valid possibilities while skipping duplicates through visited, we ensure that we only return valid results with minimal edits.</p><h3>Pattern Trigger</h3><blockquote><em>When you’re asked to </em><strong><em>generate all valid combinations</em></strong><em>, especially with constraints like </em><strong><em>minimal deletions</em></strong><em>, it’s a strong sign to use </em><strong><em>recursion or backtracking</em></strong><em>. Combine that with a memoization strategy like a </em><em>visited set, and you have a powerful pattern for solving a wide range of problems.</em></blockquote><h3>Final Thoughts</h3><p>This problem teaches more than just string manipulation:</p><ul><li>It builds your intuition for pruning recursive trees</li><li>Reinforces the importance of avoiding redundant work</li><li>And shows how careful pre-processing (like counting removals) can drastically improve performance</li></ul><p>Happy coding! ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3cbbd05ef34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[124. Binary Tree Maximum Path Sum — Leetcode Hard]]></title>
            <link>https://medium.com/@dreamchaserdiaries/124-binary-tree-maximum-path-sum-leetcode-hard-98aff72a5d4f?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/98aff72a5d4f</guid>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 07:00:30 GMT</pubDate>
            <atom:updated>2025-06-09T07:00:30.140Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/">124. Binary Tree Maximum Path Sum</a> — Leetcode Hard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIna9bj-GWuDTO1R3-K0Zw.png" /></figure><p>We will be solving it using recursion.</p><h3>Recursion Thinking Style:</h3><p>You usually think in terms of:</p><pre>int dfs(TreeNode* node) {<br>    // what does this return?<br>}</pre><h3>So define: What does dfs(node) return?</h3><p>Let’s <strong>define it like this</strong>:</p><blockquote><em>dfs(node) returns the </em><strong><em>maximum path sum </em>starting from<em> </em></strong><strong><em>node and going downward</em></strong><em> to either left or right </em><strong><em>(not both)</em></strong><em>.</em></blockquote><p>Why only one side?<br> Because if you take both sides at once, that forms a full “arch” (like going left→node→right), which can be a path <strong>in the middle</strong>, but can’t be extended further upward. So we compute that separately. ie -10,20,15 can be one path and -10,20,7 can be another. We need one with the maxSum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*ElGWDhGLOfL_-_gDsZLRiQ.png" /></figure><p>Like in above example, let’s assume the DFS(9) is returning 9 to us and DFS(20) is returning (20+15) to us.</p><p>Now we have to calculate how we are going to use DFS(node-&gt;left) and DFS(node-&gt;right) to calculate DFS(node) and what we will be retuning for this DFS(node).</p><h3>What we will be returning at particular node</h3><p>As mentioned, <em>dfs(node) returns the </em><strong><em>maximum path sum </em>starting from<em> </em></strong><strong><em>node </em></strong>hence we will be returning<strong><em> </em></strong>return max(left, right) + node-&gt;val;</p><h3>Calculation at current node</h3><p>You check if the full path <strong>passing through the current node</strong> (left + node + right) forms the <strong>maximum path sum overall. </strong>That becomes a candidate for global answer.</p><p>Wrapping up the whole thing together</p><pre>/**<br> * Definition for a binary tree node.<br> * struct TreeNode {<br> *     int val;<br> *     TreeNode *left;<br> *     TreeNode *right;<br> *     TreeNode() : val(0), left(nullptr), right(nullptr) {}<br> *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}<br> *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}<br> * };<br> */<br>class Solution {<br>public:<br>    int dfs(TreeNode* node , int &amp;ans){<br>        // base condition<br>        if(node == NULL){<br>            return 0;<br>        }<br>        int left = max(0,dfs(node-&gt;left,ans));<br>        int right = max(0,dfs(node-&gt;right,ans));<br>        // calcualtions<br>        if(left+right+node-&gt;val&gt;ans){<br>            ans=left+right+node-&gt;val;<br>        }<br>        //return statement<br>        return max(left,right)+node-&gt;val;<br>    }<br>    int maxPathSum(TreeNode* root) {<br>        int ans = INT_MIN;<br>        dfs(root,ans);<br>        return ans;<br>    }<br>};</pre><h3>Special Note</h3><p>You might have noticed this particular line- max(0,….).</p><pre>int left = max(0,dfs(node-&gt;left,ans));<br>int right = max(0,dfs(node-&gt;right,ans));</pre><p>The reason why we are doing it is-</p><p>Let’s say a child subtree returns a <strong>negative</strong> value — that means <strong>including it would <em>reduce</em> the total path sum</strong>. You definitely don’t want to include that!</p><p>So when you write:</p><pre>int left = max(0, dfs(node-&gt;left));</pre><p>You’re saying:</p><blockquote><em>“Only consider the left subtree if it contributes positively.</em></blockquote><p>Let’s go step by step with an <strong>example</strong> to make this crystal clear.</p><pre>     1<br>    / \<br>  -2   3</pre><h3>With max(0, dfs(...))</h3><p>Let’s walk through what happens when you write:CopyEdit</p><pre>int left = max(0, dfs(node-&gt;left));<br>int right = max(0, dfs(node-&gt;right));</pre><h3>Step-by-step:</h3><ul><li>Start at root 1</li><li>dfs(-2) → returns -2 → left = max(0, -2) = 0</li><li>dfs(3) → returns 3 → right = max(0, 3) = 3</li></ul><p>Now at root 1:</p><ul><li>localMax = left + right + node-&gt;val = 0 + 3 + 1 = 4</li><li>You update the global max as 4</li><li>You return max(left, right) + node-&gt;val = max(0, 3) + 1 = 4</li></ul><p>✅ <strong>Correct Answer: 4</strong></p><h3>❌ Without max(0, dfs(...))</h3><p>Now suppose your code just did:</p><pre>int left = dfs(node-&gt;left);  // no max(0, ...)<br>int right = dfs(node-&gt;right);</pre><h3>Let’s do the full trace:</h3><h4>Step 1: dfs(-2)</h4><ul><li>left = dfs(NULL) → 0</li><li>right = dfs(NULL) → 0</li><li>localMax = 0 + 0 + (-2) = -2</li><li>Global max = <strong>-2</strong></li><li>Return = max(0, 0) + (-2) = -2 → in <strong>no </strong><strong>max(0, ...)</strong> version: return -2</li></ul><h4>Step 2: dfs(3)</h4><ul><li>left = dfs(NULL) → 0</li><li>right = dfs(NULL) → 0</li><li>localMax = 0 + 0 + 3 = 3</li><li>Global max = max(-2, 3) = <strong>3</strong></li><li>Return = 3</li></ul><h4>Step 3: dfs(1)</h4><p>Now at root:</p><ul><li>left = -2</li><li>right = 3</li><li>localMax = -2 + 3 + 1 = **2** ❗</li><li>Global max = max(3, 2) = <strong>3</strong></li></ul><p>But correct answer should be 4. Hence (0,max….) is needed.</p><h3>Time Complexity</h3><h3>What happens in dfs()?</h3><p>You are doing a <strong>post-order traversal</strong>:</p><ul><li>You visit every node exactly <strong>once</strong>.</li><li>At each node:</li><li>You make <strong>constant time operations</strong>: max(), addition, comparison, etc.</li><li>The recursive calls go <strong>left and right</strong> down the tree.</li></ul><h3>⏱️ Time Complexity</h3><p>Let:</p><ul><li>n be the number of nodes in the binary tree.</li></ul><p>Each node:</p><ul><li>Is visited exactly once.</li><li>Performs <strong>O(1)</strong> work at each visit.</li></ul><p>So the <strong>total time complexity</strong> is: <strong><em>O(n)</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98aff72a5d4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10. Regular Expression Matching — Leetcode Hard]]></title>
            <link>https://medium.com/@dreamchaserdiaries/10-regular-expression-matching-leetcode-hard-ceae7a7ef321?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceae7a7ef321</guid>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Sat, 31 May 2025 07:15:21 GMT</pubDate>
            <atom:updated>2025-05-31T07:15:21.460Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://leetcode.com/problems/regular-expression-matching/">10. Regular Expression Matching</a> — Leetcode Hard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDYugykrsUlbJCQPo_yubA.png" /><figcaption>Question image</figcaption></figure><p>In this post, we’ll solve Leetcode #10 — Regular Expression Matching using recursion and optimize it with dynamic programming (memoization). We’ll break down how the pattern . and * behave and build the solution step-by-step.</p><h3>Pattern Trigger: Recursion with Overlapping Subproblems → DP</h3><p>This problem is a classic case of the <strong>Recursion + Memoization</strong> (top-down DP) pattern.</p><p>Here’s what triggers it:</p><p><strong>1.Decision at each index</strong><br> At every position i in the string s and j in the pattern p, we decide:</p><ul><li>Do we move forward?</li><li>Do we skip characters (especially due to *)?<br> This naturally forms a recursive tree.</li></ul><p><strong>2. Two choices at </strong><strong>*:</strong></p><ul><li>Skip the * and its preceding character → util(i, j+2)</li><li>Use the * to match one or more → util(i+1, j)</li></ul><p>Don’t worry all this will be explained in detail below.</p><p><strong>3. Overlapping subproblems:</strong><br> You’ll notice that the same (i, j) states get recomputed multiple times — that&#39;s a strong signal to apply <strong>memoization</strong>.</p><p><strong>4. Changing parameters:</strong><br> Only i and j change → Use a 2D DP table dp[i][j]</p><p>First, we will be solving it via recursion and then we will be optimizing it.</p><p>Suppose you are standing at i th index of string i and j th index of string j and our util function (string s, string p, int i , int j) return if there’s a valid pattern from i th index of s and j th index of p.</p><p>We have multiple option when we are standing at i and j.</p><pre>if(s[i] == p[j] || p[j] == &#39;.&#39;){<br>  // our current letter is matching so we recursively call i=on i+1 and j+1<br>   util(s,p,i+1,j+1)<br>}</pre><p>The tricky part is handling the * character, which can match <strong>zero or more</strong> of the preceding element.</p><p>Let’s assume s= ”aa” and p = “a*” and currently we are at i = 0 and j=0.</p><p>We checked that p[j+1] = ’*’, so it will be matching zero or more of the <strong>preceding</strong> element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*_6lmefcNLrjyao6qiF9eOQ.png" /></figure><p>Code for the same is —</p><pre>class Solution {<br>public:<br>    bool util(string s, string p, int i , int j){<br>       // base case<br>       if(i == s.length() &amp;&amp; j==p.length()){<br>        return true;<br>       }<br>       // if pattern gets finished but string is not<br>       if(j==p.length()){<br>        return false;<br>       }<br>       bool currentMatch  = (i &lt; s.length()) &amp;&amp; (s[i] == p[j] || p[j] == &#39;.&#39;);<br><br>       if(j+1&lt;p.length() &amp;&amp; p[j+1] == &#39;*&#39;){<br>        // Don&#39;t match the character of s[i]<br>        bool zeroMatch = util(s,p,i,j+2);<br><br>        // if the current character match, see if there are more of the same element<br>        bool oneOrMoreMatch = currentMatch &amp;&amp; util(s,p,i+1,j);<br>        return zeroMatch || oneOrMoreMatch;<br>       }<br>       if(currentMatch) {<br>            return util(s,p,i+1,j+1);<br>       }<br>       return false;<br>    }<br>// main function<br>    bool isMatch(string s, string p) {<br>        return util(s,p,0,0);<br>    }<br>};</pre><p>Once the recursive code is done, we just have to memoize it when we see the overlapping problems, in case we do have them.</p><h3>Time Complexity for the recursive code</h3><p>Let:</p><ul><li>n = s.length()</li><li>m = p.length()</li></ul><p><strong>Time Complexity: </strong><strong>O(2^(n + m))</strong><br> Because each * can potentially branch into 2 paths, and you recurse over both string and pattern.</p><h3>Memoization</h3><p>To memoize it, look for the parameters that are changing in recursive code and make a dp table for the same. In our case i and j are changing hence we would be creating a table for the same and updating the return statements accordingly. We memoize using a 2D table dp[i][j], where each entry stores whether s[i:] matches p[j:].</p><pre>class Solution {<br>public:<br>    bool util(string s, string p, int i , int j, vector&lt;vector&lt;int&gt;&gt;&amp;dp){<br>       // base case<br>       if(i == s.length() &amp;&amp; j==p.length()){<br>        return dp[i][j]= true;<br>       }<br>       // if pattern gets finished but string is not<br>       if(j==p.length()){<br>        return dp[i][j]=false;<br>       }<br>       if(dp[i][j]!=-1) {<br>        return dp[i][j];<br>       }<br>       bool currentMatch  = (i &lt; s.length()) &amp;&amp; (s[i] == p[j] || p[j] == &#39;.&#39;);<br><br>       if(j+1&lt;p.length() &amp;&amp; p[j+1] == &#39;*&#39;){<br>        // Don&#39;t match the character of s[i]<br>        bool zeroMatch = util(s,p,i,j+2,dp);<br><br>        // if the current character match, see if there are more of the same element<br>        bool oneOrMoreMatch = currentMatch &amp;&amp; util(s,p,i+1,j,dp);<br>        return dp[i][j]= zeroMatch || oneOrMoreMatch;<br>       }<br>       if(currentMatch) {<br>            return dp[i][j]= util(s,p,i+1,j+1,dp);<br>       }<br>       return dp[i][j]= false;<br>    }<br>    bool isMatch(string s, string p) {<br>        vector&lt;vector&lt;int&gt;&gt;dp(s.length()+1,vector&lt;int&gt;(p.length()+1,-1));<br>        return util(s,p,0,0,dp);<br>    }<br>};</pre><h3>Time Complexity</h3><p>Since we are memoizing it</p><p><strong>Time = (Number of States) × (Work per State)</strong></p><ul><li>States: (i, j) where i ∈ [0, n], j ∈ [0, m] → <strong>O(n × m)</strong></li><li>Each state does <strong>O(1)</strong> work (constant checks + up to 2 recursive calls)</li></ul><p><strong>Final Time Complexity: O(n × m).</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceae7a7ef321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[23. Merge k Sorted Lists — Leetcode Hard Question]]></title>
            <link>https://medium.com/@dreamchaserdiaries/23-merge-k-sorted-lists-leetcode-hard-question-79f7fbfc2f19?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/79f7fbfc2f19</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[grind]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Sat, 24 May 2025 04:47:16 GMT</pubDate>
            <atom:updated>2025-06-04T02:56:54.804Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://leetcode.com/problems/merge-k-sorted-lists/">23. Merge k Sorted Lists</a> — Leetcode Hard Question</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFwPQjz8Y4Y6ouKFi5ccYA.png" /></figure><p>My intuition- The first thing i noticed is the key word — *k sorted*. Since we need access to min elements of k lists quickly, the best data structure for the same would be a min-heap which can give us minimum elements quickly.</p><p>What we can do is initially store all the first elements of all the lists in the heap. Keep taking the min out, insert it into answer list and put the popped element’s next node in the heap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKmyuI2jWQTJlNZMyGbCjA.png" /><figcaption>Flow diagram of our intitution!</figcaption></figure><p><strong>Key Problems — Min Heap Declaration with a compare function</strong></p><p>General structure — priority_queue&lt;DataType&gt;, vector&lt;DataType&gt;, decltype(Comparefunction)&gt; minHeapName(Comparefunction);</p><pre>auto cmp = [](ListNode* a, ListNode* b) {<br>            return a-&gt;val &gt; b-&gt;val;<br>        };<br><br>priority_queue&lt;ListNode*, vector&lt;ListNode*&gt;, decltype(cmp)&gt; pq(cmp);</pre><p>The whole code with proper comments are given below-</p><p>We use a dummy node to simplify handling the head pointer. We’ll return dummy-&gt;next as the real head of the merged list.</p><pre>/**<br> * Definition for singly-linked list.<br> * struct ListNode {<br> *     int val;<br> *     ListNode *next;<br> *     ListNode() : val(0), next(nullptr) {}<br> *     ListNode(int x) : val(x), next(nullptr) {}<br> *     ListNode(int x, ListNode *next) : val(x), next(next) {}<br> * };<br> */<br>class Solution {<br>public:<br>    ListNode* mergeKLists(vector&lt;ListNode*&gt;&amp; lists) {<br>        auto cmp = [](ListNode *a, ListNode * b){<br>            return a-&gt;val&gt;b-&gt;val;<br>        };<br>        priority_queue&lt;ListNode*, vector&lt;ListNode*&gt;, decltype(cmp)&gt; pq(cmp);<br>        // putting the first elements in the heap<br>        for(int i = 0;i&lt;lists.size();i++){<br>            if (lists[i]) { //  only push non-null heads else cmp function will throw an error<br>                pq.push(lists[i]);<br>            }<br>        }<br>        // dummy node as head for the new list<br>        ListNode * head = new ListNode(0);<br>        ListNode * temp = head;<br>        while(!pq.empty()){<br>            ListNode* currentNode = pq.top();<br>            pq.pop();<br>            if(currentNode-&gt;next){<br>                pq.push(currentNode-&gt;next);<br>            }<br>            temp-&gt;next = currentNode;<br>            temp = temp-&gt;next;<br>        }<br>        return head-&gt;next;<br><br>    }<br>};</pre><p>And viola, you solved the hard question easily!</p><p><strong>Time Complexity</strong></p><p>Let’s assume there are N nodes in all the lists together</p><pre>while(!pq.empty()){ <br>// this will run for N times as all the nodes will go in the heap atleast once.<br>}</pre><p>and log k for heapification — k because at max, at a time, only k elements will be there in the heap.</p><p>Hence</p><p><strong>Time Complexity = O(n log k).</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79f7fbfc2f19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[336. Palindrome Pairs]]></title>
            <link>https://medium.com/@dreamchaserdiaries/336-palindrome-pairs-3184635b3cff?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3184635b3cff</guid>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Sat, 03 May 2025 01:55:03 GMT</pubDate>
            <atom:updated>2025-05-31T10:53:36.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUeC7y6cw7WH3TtZwUwlxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NPXjMX4mcY8XJ2Ge_1uFQ.png" /></figure><p>My first approach was a brute-force solution where I would check every possible pair of words and see if their concatenation forms a palindrome. However, this would take approximately O(n²) time, which isn’t efficient for larger inputs.</p><pre>vector&lt;vector&lt;int&gt;&gt; palindromePairs(vector&lt;string&gt;&amp; words) {<br>        vector&lt;vector&lt;int&gt;&gt; ans;<br>        for(int i = 0; i&lt;words.size();i++){<br>            for(int j = 0; j&lt;words.size();j++){<br>                if (i == j) continue;  // skip pairing word with itself<br>                if(isPalindrome(words[i]+words[j])){<br>                    // i, j forms a palindrome<br>                    vector&lt;int&gt; temp;<br>                    temp.push_back(i);<br>                    temp.push_back(j);<br>                    ans.push_back(temp);<br>                }<br>            }<br>        }<br>        return ans;<br>    }</pre><p>Now onto optimization. Not gonna lie, it took me quite some time to understand what we are trying to do. Even after going through multiple resources, i couldn’t exactaly figure it out.</p><h3>For each word in the list, we try to find out:</h3><blockquote><em>“Can I put another word in front or at the end of this word to make a palindrome?”</em></blockquote><p>To do this, we:</p><ol><li><strong>Split the word</strong> into two parts — left and right.</li><li>If the <strong>left part is a palindrome</strong>, we check if the <strong>reverse of the right part</strong> exists in the list.</li><li>If the <strong>right part is a palindrome</strong>, we check if the <strong>reverse of the left part</strong> exists in the list.</li><li>If such a word is found, we’ve got a valid pair.</li><li>Let’s apply the <strong>core idea</strong> on this exact list:</li></ol><pre>words = [&quot;abcd&quot;, &quot;dcba&quot;, &quot;lls&quot;, &quot;s&quot;, &quot;sssll&quot;]</pre><h3>Let’s take the word &quot;abcd&quot; (index 0).</h3><p>Try splitting it at every position:</p><h3>1. &quot;a&quot; | &quot;bcd&quot;</h3><ul><li>&quot;a&quot; is a palindrome ✅</li><li>Reverse of &quot;bcd&quot; is &quot;dcb&quot; ❌ not in list<br> ➡️ If &quot;dcb&quot; was in the list, then &quot;dcb&quot; + &quot;abcd&quot; would form a palindrome.<br> In that case, we&#39;d add the pair: <strong>[index(&quot;dcb&quot;), index(&quot;abcd&quot;)]</strong></li></ul><h3>2. &quot;abc&quot; | &quot;d&quot;</h3><ul><li>&quot;d&quot; is a palindrome ✅</li><li>Reverse of &quot;abc&quot; is &quot;cba&quot; ❌ not in list<br> ➡️ No match</li></ul><h3>3. &quot;&quot; | &quot;abcd&quot;</h3><ul><li>Left side is empty → that’s always a palindrome ✅</li><li>Reverse of &quot;abcd&quot; is &quot;dcba&quot; → ✅ found at index 1<br> ➡️ Add pair: <strong>[1, 0]</strong></li></ul><h3>4. &quot;abcd&quot; | &quot;&quot;</h3><ul><li>Right side is empty → palindrome ✅</li><li>Reverse of &quot;abcd&quot; = &quot;dcba&quot; → ✅<br> ➡️ Add pair: <strong>[0, 1]</strong></li></ul><h3>📝 Final Rule Summary</h3><ul><li>If <strong>left part is a palindrome</strong> and <strong>reverse of right exists</strong>,<br> then we add: <strong>[index of reverse(right), index of current word]</strong></li><li>If <strong>right part is a palindrome</strong> and <strong>reverse of left exists</strong>,<br> then we add: <strong>[index of current word, index of reverse(left)]</strong></li></ul><p><strong><em>Instead of checking every possible pair</em></strong><em>,<br>We take each word and ask:</em>“What word do I need to add to the front or back to make a palindrome?”<em>Then, we check if that word (in reverse) already exists in the list.</em></p><h3>Why it works:</h3><p>Because a <strong>palindrome mirrors around its center</strong>, so if one half is already a palindrome, you just need the <strong>reverse of the other half</strong> to complete it.</p><p>Code for the same</p><pre>class Solution {<br>public:<br>    bool isPalindrome(string &amp;s) {<br>        int l = 0, r = s.size() - 1;<br>        while (l &lt; r) {<br>            if (s[l++] != s[r--]) return false;<br>        }<br>        return true;<br>    }<br>    vector&lt;vector&lt;int&gt;&gt; palindromePairs(vector&lt;string&gt;&amp; words) {<br>        vector&lt;vector&lt;int&gt;&gt; result;<br>        unordered_map&lt;string,int&gt; wordMap;<br>        // to find out the index of reverse of a string. For Quick lookup.<br>        for(int i =0;i&lt;words.size();i++){<br>            wordMap[words[i]] = i;<br>        }<br>        for(int i = 0;i&lt;words.size();i++){<br>            // split at every index of that particular word;<br>            for(int j = 0;j&lt;=words[i].size();j++){<br>                string word1 = words[i].substr(0, j);<br>                string word2 = words[i].substr(j); <br>                // check word1 palindrome<br>                if(isPalindrome(word1)){<br>                    // a | bcd --- &gt;&gt;&gt; a is palindrome, check if reverse(bcd) exists or not in map<br>                    string reversedWord2 = word2;<br>                    reverse(reversedWord2.begin(), reversedWord2.end());<br>                    if (wordMap.count(reversedWord2) &amp;&amp; wordMap[reversedWord2] != i) {<br>                        // dcb | abcd would be ans<br>                        result.push_back({wordMap[reversedWord2], i});<br>                    }<br>                }<br>                // j != words[i].size() to avoid duplicates<br>                if(j != words[i].size() &amp;&amp; isPalindrome(word2)){<br>                    // a | bcd --- &gt;&gt;&gt; a is palindrome, check if reverse(bcd) exists or not in map<br>                    string reversedWord1 = word1;<br>                    reverse(reversedWord1.begin(), reversedWord1.end());<br>                    if (wordMap.count(reversedWord1) &amp;&amp; wordMap[reversedWord1] != i) {<br>                        // dcb | abcd would be ans<br>                        result.push_back({i,wordMap[reversedWord1]});<br>                    }<br>                }<br>            }<br>        }<br>        return result;<br>    }<br>};</pre><h3>Important Points</h3><h3>wordMap[reversedWord2] != i</h3><pre>if (wordMap.count(reversedWord2) &amp;&amp; wordMap[reversedWord2] != i) {<br>}</pre><p>The reason why we are adding this is suppose you have string = “S”. Now we we do the subset</p><p>1- left = “ “ and right = s; left is a palindrome and reverse(right) also exits in map which is the word itself. We don’t want that in the question. Hence before adding, we check the condition that <strong>wordMap[reversedWord2] != i.</strong></p><h3>if(j != words[i].size() &amp;&amp; isPalindrome(word2)){</h3><pre>if(j != words[i].size() &amp;&amp; isPalindrome(word2)){</pre><p>The reason why we are doing this is- suppose you have abcd and dcba</p><p>While doing subsets of abcd, we will get left = “abcd” and right = “ ”. Since right is a palindrome, we would’ve added index of abcd and dcba which is 0 , 1.</p><p>Now while doing dcba, we would’ve gotten left = “ ” and right = “ dcba”. Left is palindrome, reverse of right exists hence index of(reverse of right) and index of word = (0, 1) again in the list.</p><p>Add j != word.size() to skip the <strong>right == &quot;&quot;</strong> case in the second check — because the <strong>left == &quot;&quot;</strong> case already covered it.</p><h3>Time Complexity</h3><ul><li>Let n = number of words, k = average word length</li><li>For each word (n), we try all splits (k), and for each split:</li><li>We check for palindrome and reverse — both take O(k)</li><li>So total time:<br> <strong>O(n × k × k) = O(n × k²)</strong></li></ul><p>Phew. That was a long question. Try to do a dry run multiple time and see to practice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3184635b3cff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Scalable Web Application on AWS: AMI, Launch Templates, Auto Scaling Groups, and Load…]]></title>
            <link>https://medium.com/@dreamchaserdiaries/building-a-scalable-web-application-on-aws-ami-launch-templates-auto-scaling-groups-and-load-6f5973d7ac40?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f5973d7ac40</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[autoscaling-group]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[autoscaling]]></category>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 19:50:25 GMT</pubDate>
            <atom:updated>2025-04-28T19:50:25.908Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Scalable Web Application on AWS: AMI, Launch Templates, Auto Scaling Groups, and Load Balancers Explained</h3><p>When you build a web application, your goal is not just to make it run — you want it to stay available even if <strong>hundreds</strong> or <strong>thousands</strong> of users arrive at once.</p><p>In a traditional server setup, you might manually launch more servers when traffic grows. But in the cloud, we aim for automation and resilience.</p><p>AWS provides a powerful combination of services that work together to achieve this:</p><ul><li><strong>Amazon Machine Image (AMI)</strong> to package your application.</li><li><strong>Launch Template</strong> to define how servers should be created.</li><li><strong>Auto Scaling Group (ASG)</strong> to automatically add or remove servers based on traffic.</li><li><strong>Target Group</strong> to track healthy servers.</li><li><strong>Application Load Balancer (ALB)</strong> to smartly route user requests to healthy servers.</li></ul><p>In this blog, we’ll walk through <strong>how these pieces connect together</strong> to build a <strong>scalable, fault-tolerant cloud backend</strong> — the kind of system that powers real-world apps at companies like Netflix and Airbnb.</p><p>Let’s start by understanding <strong>what each component does</strong>, and <strong>how they work together</strong> to create an elastic, self-healing web application architecture!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVn07fY3_RvDorh1ol8sOA.png" /></figure><p>Creating an <strong>Auto Scaling Environment</strong> typically includes these key steps:</p><ul><li><strong>Create a Custom AMI(optional)</strong></li><li><strong>Create a Launch Template or Configuration</strong><br> — Define the AMI, instance type, key pair, security groups, etc.</li><li><strong>Create a Target Group</strong><br> — A group of instances that the Load Balancer routes traffic to.</li><li><strong>Create an Application Load Balancer (ALB)</strong><br> — Distributes incoming traffic across multiple instances for high availability.</li><li><strong>Create an Auto Scaling Group (ASG)</strong><br> — Link it to the Launch Template and Target Group, set scaling policies (min, max, desired number of instances).</li><li><strong>Configure Scaling Policies (Optional)</strong><br> — Define rules to automatically add/remove instances based on metrics like CPU utilization.</li></ul><pre>[Users on Internet]<br>                  ↓<br>        [Load Balancer (ALB)]<br>                  ↓<br>(Forwards request based on Listener rules)<br>                  ↓<br>        [Target Group (webserver-app)]<br>                  ↓<br>(Contains registered targets: EC2 instances)<br>                  ↓<br>     [Auto Scaling Group (ASG)]<br>                  ↓<br>(Launches EC2 Instances based on load)<br>                  ↓<br>        [Launch Template]<br>                  ↓<br>(Defines how to launch EC2s, and points to)<br>                  ↓<br>            [AMI]</pre><h3>(Optional Step) <strong>Create a Custom AMI</strong></h3><p>An Amazon Machine Image (AMI) captures the configuration of your EC2 instance, including the operating system, application code, and settings. Creating an AMI ensures that new instances launched by the Auto Scaling Group have the same setup.”When you create an AMI from an EC2 instance, you’re saying:</p><p>Steps to create an AMI are —</p><ol><li><strong>Select your instance — </strong>Check the box next to the instance you want to create an AMI from.</li></ol><p>2.<strong> Actions ➔ Create Image — </strong>At the top, click <strong>Actions</strong> ➔ <strong>Create image</strong>.</p><p>3.<strong> Fill in the image details</strong></p><p>3.1<strong> Image name</strong>: Give it a friendly name (e.g., <em>MyWebServer-AMI</em>).</p><p>3.2<strong> Image description</strong>: (Optional) Add notes like “AMI of server with Nginx configured.”</p><p>3.3<strong> No reboot</strong>: You can check this if you don’t want AWS to reboot the instance (usually it’s fine to let AWS reboot).</p><p>4. Click <strong>Create Image</strong>.</p><p>You can see its status in the <strong>AMIs</strong> section (left sidebar ➔ <strong>Images ➔ AMIs</strong>).</p><h3>Step — 1 <strong>Create a Launch Template or Configuration</strong></h3><p>Launch Template is basically an instruction manual that tells AWS: “Use <em>this</em> AMI”, “Use <em>this</em> instance type” or “Use <em>this</em> key pair”. To create an Launch template follow the following steps.</p><ul><li>In the EC2 dashboard left sidebar, click <strong>Launch Templates</strong>.</li><li>Click <strong>Create launch template</strong>.</li><li><strong>Fill in launch template details — Name </strong>: Give it a name like MyWebServer-LaunchTemplate, <strong>AMI </strong>: Choose <strong>your custom AMI</strong> you just created! (It’ll show in the dropdown) or any AMI you want, <strong>Instance type </strong>: Choose something like t2.micro or any size you need, <strong>Key pair </strong>: Select your key pair if you want SSH access, <strong>Security group</strong>: Make sure the security group allows access (e.g., HTTP, SSH).</li><li>Leave other settings default unless you have specific needs.</li><li>Click <strong>Create launch template</strong>.</li></ul><p>After defining how instances will be created and scaled, the next important step is setting up a Load Balancer. This ensures that user traffic is intelligently routed across healthy instances.</p><h3>Step- 2 Create an Application Load Balancer</h3><p>You are setting up <strong>an Application Load Balancer (ALB)</strong> because:</p><ol><li><strong>You will have multiple EC2 instances</strong> (Auto Scaling will create them later).</li><li><strong>You need a single public entry point (one URL/IP)</strong> for users to access your application — even though multiple servers will serve them in the backend.</li><li><strong>You want automatic distribution of traffic</strong> across healthy servers.</li><li><strong>You want health checks</strong> so AWS knows if any server fails and can stop sending traffic there.</li></ol><pre>[Users (Internet)]<br>         ↓<br>[Application Load Balancer (ALB)]<br>         ↓<br>[Target Group (TG)]<br>         ↓<br>[Auto Scaling Group (ASG)]<br>         ↓<br>[EC2 Instances (created from Launch Template using AMI)]</pre><h4>How to create an Application Load balancer?</h4><ul><li>In the <strong>AWS Management Console</strong>, go to <strong>Services ➔ EC2 ➔ Load Balancers</strong>.</li><li>Click <strong>Create Load Balancer</strong>, and under <strong>Application Load Balancer</strong>, choose <strong>Create</strong>.</li><li>Enter a <strong>name</strong> for your load balancer eg. webserverloadbalancer and select a <strong>VPC</strong> (you can use the default or a custom one).</li><li>Select <strong>two public subnets</strong> in different Availability Zones (this makes the load balancer highly available).</li><li>Under <strong>Security Groups</strong>, select or create a group that <strong>allows HTTP (port 80)</strong> traffic.</li></ul><p>Now we will create a target group (if not created before )— A <em>target group</em> defines where to <em>send</em> traffic that comes into the load balancer. The Application Load Balancer can send traffic to multiple target groups based on the URL of the incoming request, such as having requests from mobile apps go to a different set of servers.</p><ul><li>In the <strong>Listeners and Routing</strong> section, <strong>create a Target Group</strong> (choose <strong>Instances</strong> as the target type).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePcAEfFUWhDt10unXq_XuA.png" /></figure><ul><li>Choose Create target group. A new browser tab opens. Choose a target type: Choose Instances.</li><li>Target group name, enter the name eg- webserver-app</li><li>Set a <strong>health check path</strong> like /index.php, and adjust the <strong>health check settings</strong> if you want faster checks.</li><li>(Optional) <strong>Skip registering targets</strong> if you don’t have instances yet — you can add them later.</li><li>Back in the Load Balancer setup, <strong>link the Listener</strong> to your new Target Group. For the <strong>Listener HTTP:80</strong> row, set the Default action to forward to <strong>webserver-app</strong>.</li><li>Review all settings, click <strong>Create Load Balancer</strong>, and then <strong>View Load Balancer</strong> once it’s ready.</li></ul><p>The Load Balancer routes incoming traffic to the Target Group, which comprises EC2 instances managed by the Auto Scaling Group.</p><p>With the Launch Template and load balancer ready, it’s time to create an Auto Scaling Group. This group will handle dynamic scaling of your EC2 instances based on real-time demand.”</p><h3>Step — 4 Create an auto scaling group</h3><p>Now while creating auto scaling group, we will be specifying Launch template and associating it with the Target Group so that any new instances launched are automatically registered, allowing the Load Balancer to distribute traffic to them.</p><ol><li>In the <strong>EC2 dashboard</strong>, go to <strong>Auto Scaling Groups</strong> ➔ click <strong>Create Auto Scaling Group</strong>.</li><li>Give a name (e.g., WebServersASGroup), select your <strong>Launch Template</strong> (e.g., WebServerLaunchTemplate), and click <strong>Next</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*RE5CPNiJWRnuMryj2vbTRw.png" /></figure><p>3. Choose your <strong>VPC</strong> and <strong>private subnets</strong> where instances should launch.</p><p>4. Attach the group to your <strong>existing Load Balancer</strong>, selecting the <strong>webserver-app</strong> target group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMWD-zhX7W1eU8NZ1VtTBA.png" /></figure><p>5. Enable <strong>group metrics collection</strong> in <strong>CloudWatch</strong> and click <strong>Next</strong>.</p><p>6. Set <strong>Desired = 2</strong>, <strong>Min = 2</strong>, <strong>Max = 4</strong> instances.</p><p>7. In Scaling Policies - Add a <strong>Target Tracking Scaling Policy</strong>: track <strong>Average CPU Utilization</strong>, target value <strong>45%</strong>.</p><p><strong>Analysis</strong>: If average CPU Utilization exceeds this 45%, additional instances will be launched. If average CPU Utilization falls below this target, instances <em>might</em> be terminated.</p><p>8. Skip notifications, add a <strong>tag</strong> (Key: Name, Value: WebApp), and click <strong>Next</strong>.</p><p>9. Review everything and click <strong>Create Auto Scaling Group.</strong></p><h3>🚀 Conclusion</h3><p>By combining AMIs, Launch Templates, Auto Scaling Groups, Target Groups, and Load Balancers, you can build a <strong>highly scalable</strong>, <strong>fault-tolerant</strong> infrastructure on AWS.<br> This architecture allows your application to handle varying amounts of traffic <strong>automatically</strong>, without manual intervention — the backbone of modern cloud-native applications.</p><p>Now that you understand how these components fit together, I encourage you to try building your own scalable backend on AWS!<br> Experiment with different scaling policies, add monitoring with CloudWatch, and fine-tune your setup for real-world production needs.</p><p>🔖 <em>“Save this post for future reference — building cloud-native architectures becomes easier when you have the roadmap!”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f5973d7ac40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Website on S3 using AWS CLI.]]></title>
            <link>https://medium.com/@dreamchaserdiaries/create-a-website-on-s3-using-aws-cli-8568628ec6f0?source=rss-e2ec5dbb63fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8568628ec6f0</guid>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws-cli]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[static-websites]]></category>
            <dc:creator><![CDATA[Yashika Ahlawat]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 21:35:50 GMT</pubDate>
            <atom:updated>2025-04-26T21:35:50.317Z</atom:updated>
            <content:encoded><![CDATA[<p>We are <strong>hosting a static website</strong> (HTML, CSS, JS files) using <strong>Amazon S3 through AWS CLI</strong>.</p><p>Since S3 is normally just cloud storage (like Dropbox or Google Drive), we are <strong>configuring it</strong> to behave like a <strong>public web server</strong>. The steps we would be following are-</p><pre>1. Create an S3 bucket using cli.<br>2. Configure permissions.<br>3. Enable static website hosting.<br>4. Upload website files.<br>5. Build a script (update-website.sh){In case you want to update the content<br>   in the files and don&#39;t want to repeat the same steps again.<br>6. Make the script executable (chmod +x).<br>7. Run the script (./deploy-website.sh).<br>8. Visit the website URL | See your live website hosted from S3</pre><p>Before we move forward, <strong>let’s clarify something important</strong>:<br>We are assuming that you have already <strong>launched your EC2 instance</strong> as part of the setup process, and that the instance <strong>comes preloaded</strong> with a folder named ~/sysops-activity-files containing the file static-website.tar.gz.</p><p>In our case, the file name is <strong>static-website.tar.gz</strong>, but <strong>you can use any archive file</strong> containing your website files. If you&#39;re using your own project, feel free to <strong>replace this filename</strong> with the one you are working with.</p><p><strong>In simple terms</strong>:<br>The file static-website.tar.gz is <strong>already present</strong> on your EC2 instance, and you are now going to <strong>unpack</strong> it to access the website files (like index.html, images, stylesheets, etc.) needed for static website hosting.</p><h3>Task 1: SSH into your EC2 instance from your terminal(Mac/Linux Users Only</h3><h4>1. Download the PEM File</h4><p>When launching your EC2 instance, download the <strong>PEM key file</strong> (example: labsuser.pem).<br> Save it somewhere safe (e.g., your <strong>Downloads</strong> folder). You won&#39;t be able to download it again.</p><h4>2. Open Terminal and Go to Your PEM File</h4><p>Navigate to the directory where your PEM file is saved and aka the PEM file read-only by running the following command</p><pre>chmod 400 labsuser.pem</pre><p>chmod = change mode (i.e., change file permissions)</p><p>400 = set permission to &quot;read-only&quot; for the owner and no permissions for anyone else. Specifically : <strong>4</strong> = Read permission for the owner <strong>0</strong> = No, permission for the group , <strong>0</strong> = No permission for others.</p><h4>3. Connect to Your EC2 Instance</h4><ul><li>In the AWS Console, go to <strong>EC2 → Instances</strong> and copy your instance’s <strong>IPv4 Public IP</strong>.</li><li>Then SSH into the instance:</li></ul><pre>ssh -i labsuser.pem ec2-user@&lt;public-ip&gt;</pre><h3>Task 2: Configure the AWS CLI</h3><p>Why do we need to configure AWS CLI? Because the AWS CLI needs to know: Who you are (your credentials),Which region you want to work in, What format you want your results in.</p><p>Without configuration, the CLI doesn’t know which AWS account to connect to, so it cannot perform any action like creating a bucket, uploading files, launching EC2 instances, etc.</p><p>From your terminal, where you have ssh’ed into your EC2 instance, run:</p><pre>aws configure</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPgg0IZM-_WeunpqVClMBw.png" /></figure><h3>Task 3: Extract the files that you need for this activity</h3><p>Back in the SSH terminal, extract the files that you need for hosting website by running the following commands(Below are the files that I needed, please make sure that you are uploading your files:</p><pre>cd ~/sysops-activity-files <br>tar xvzf static-website.tar.gz</pre><h3>Task 4: Create and Update bucket controls/Upload files to Amazon S3 by using the AWS CLI.</h3><p>1. Create the s3 bucket from aws cli. We will be using aws s3api create-bucket api to create an S3 bucket.</p><pre>aws s3api create-bucket --bucket your-bucket-name --region your-region --create-bucket-configuration LocationConstraint=your-region</pre><p>2. Set Bucket Ownership Controls</p><pre>aws s3api put-bucket-ownership-controls \<br>--bucket &lt;my-bucket&gt; \<br>--ownership-controls &quot;Rules=[{ObjectOwnership=BucketOwnerPreferred}]&quot;</pre><p><strong>What’s happening?</strong></p><ul><li>You’re saying: “If someone uploads something into my bucket, I (the bucket owner) will automatically own it.”</li><li>This avoids weird permission issues when someone else uploads on your behalf.</li></ul><p>3. Turn off “block public access” settings</p><pre>aws s3api put-public-access-block \<br>--bucket &lt;my-bucket&gt; \<br>--public-access-block-configuration &quot;BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false&quot;</pre><ul><li>S3 buckets by default <strong>block</strong> public access.</li><li>Here you are <strong>allowing public access</strong>, because <strong>you want a public website</strong>.</li></ul><h4>(Optional)Set a Bucket Policy for Public Access</h4><p>While setting ACLs (public-read) works, the more <strong>standard AWS best practice</strong> is to apply a <strong>Bucket Policy</strong> that allows anyone to read the objects in your S3 bucket.</p><p>You can add this policy by running:</p><pre>aws s3api put-bucket-policy --bucket your-bucket-name --policy &#39;{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: &quot;*&quot;,<br>      &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::your-bucket-name/*&quot;<br>    }<br>  ]<br>}&#39;</pre><h4>Why after public access block and ownership controls?</h4><p>Because:</p><ul><li><strong>Public Access Block</strong> settings <strong>must first be disabled</strong> — otherwise your bucket would <strong>reject</strong> public policies.</li><li><strong>Ownership controls</strong> ensure your files are properly owned before you open up access.</li><li>Then, once the bucket is ready, you attach the <strong>Bucket Policy</strong> to allow public reads safely.</li></ul><p>4. Enable static website hosting</p><pre>aws s3 website s3://&lt;my-bucket&gt;/ --index-document index.html</pre><ul><li>Tells S3: “Host my files as a <strong>static website</strong>.”</li><li>Specifies that index.html will be the homepage.</li></ul><p>5. Upload website files to the bucket</p><pre>aws s3 cp . s3://&lt;my-bucket&gt;/ --recursive --acl public-read</pre><ul><li><strong>cp .</strong> = copy everything from the current directory</li><li><strong>--recursive</strong> = copy all folders and subfolders</li><li><strong>--acl public-read</strong> = set all uploaded files to be <strong>public</strong> (so anyone can access them)</li></ul><p>6. Access your website</p><ul><li>Go back to the AWS console → open your bucket → <strong>Properties tab</strong> → find the <strong>Static website hosting</strong> section.</li><li>Click the <strong>website endpoint link</strong> (example: http://your-bucket.s3-website-us-east-1.amazonaws.com) to open your site.</li></ul><p>✿ If you want ready-to-copy script that automatically does both upload + extract + list the files, you can make a bash script will all the commands in and the execute the script as follows-</p><pre>#!/bin/bash<br><br># Set your bucket name<br>BUCKET_NAME=&quot;your-bucket-name&quot;<br><br># Step 1: Set ownership controls<br>aws s3api put-bucket-ownership-controls \<br>  --bucket $BUCKET_NAME \<br>  --ownership-controls &quot;Rules=[{ObjectOwnership=BucketOwnerPreferred}]&quot;<br><br># Step 2: Allow public access<br>aws s3api put-public-access-block \<br>  --bucket $BUCKET_NAME \<br>  --public-access-block-configuration &quot;BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false&quot;<br><br># Step 3: Enable static website hosting<br>aws s3 website s3://$BUCKET_NAME/ --index-document index.html<br><br># Step 4: Upload all files to S3 bucket, make them public<br>aws s3 cp . s3://$BUCKET_NAME/ --recursive --acl public-read<br><br># Step 5: Confirm upload<br>echo &quot;Website files uploaded successfully to s3://$BUCKET_NAME/&quot;<br><br># Step 6: Show Website URL<br>echo &quot;Your website is live at:&quot;<br>echo &quot;http://$BUCKET_NAME.s3-website-$(aws configure get region).amazonaws.com&quot;</pre><p>How to use it:</p><p>Copy this into a file.</p><pre>vi deploy-website.sh</pre><ol><li>Paste the above script.</li><li>Save and quit (ESC, then :wq, then Enter).</li><li>Make the script executable:</li></ol><pre>chmod +x deploy-website.sh</pre><ul><li>chmod → <strong>change mode</strong> = change permissions of a file</li><li>+x → <strong>add executable permission</strong> (the x stands for executable)</li><li>deploy-website.sh → the <strong>file you want to make executable</strong></li></ul><p>4. Run it.</p><pre>./deploy-website.sh</pre><h3>Task 5: Create a batch file to make updating the website easily repeatable.</h3><ol><li>Create an empty script file</li></ol><pre>cd ~           # Go to your home directory<br>touch update-website.sh  # Create a new empty file called &#39;update-website.sh&#39;</pre><p>2. Edit the script file</p><pre>vi update-website.sh</pre><p>3. Type the following inside the update-website.sh</p><pre>#!/bin/bash<br>aws s3 cp ~/sysops-activity-files/ s3://&lt;my-bucket&gt;/ --recursive --acl public-read</pre><ul><li>#!/bin/bash → tells Linux: &quot;this is a <strong>bash script</strong>.&quot;</li><li>aws s3 cp ... → your <strong>file upload command</strong> (automated).</li></ul><p>After typing, save and exit:</p><ul><li>Press ESC</li><li>Then type :wq</li><li>Then press Enter</li></ul><p>(That means “write and quit” in vi.)</p><p>4. Make script executable</p><pre>chmod +x update-website.sh</pre><p>5. Modify your website(any file)</p><pre>vi sysops-activity-files/index.html</pre><p>6. Run the script to update S3</p><pre>./update-website.sh</pre><h3>Making Your Upload Script More Efficient with aws s3 sync</h3><p>Until now, you were using this command to upload your files:</p><pre>aws s3 cp . s3://your-bucket-name/ --recursive --acl public-read</pre><p>This copies <strong>all files</strong> every time — even files that <strong>haven’t changed</strong>.<br> That’s inefficient, especially for bigger websites.</p><h3>🔥 A better way: Use aws s3 sync</h3><p>You can replace your aws s3 cp line with:</p><pre>aws s3 sync . s3://your-bucket-name/ --acl public-read</pre><p>What sync does:</p><ul><li>Only uploads new or changed files.</li><li>Skips unchanged files to save time and bandwidth.</li></ul><p>And that’s it! 🚀<br> You have now successfully:</p><ul><li>Launched an EC2 instance and connected via SSH</li><li>Created an S3 bucket and configured it for static website hosting</li><li>Uploaded your website files</li><li>Automated updates using a custom bash script</li><li>(Optionally) Secured your S3 bucket with proper public access policies</li></ul><p>With this setup, you can deploy changes to your website in <strong>seconds</strong> — directly from your terminal!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8568628ec6f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>