<?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 Mithlesh Kumar on Medium]]></title>
        <description><![CDATA[Stories by Mithlesh Kumar on Medium]]></description>
        <link>https://medium.com/@mithlesh.kumar.4257?source=rss-55461a58e178------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ykpXcX0Y4C9bLxdA.</url>
            <title>Stories by Mithlesh Kumar on Medium</title>
            <link>https://medium.com/@mithlesh.kumar.4257?source=rss-55461a58e178------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:35:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mithlesh.kumar.4257/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[Fast & Slow Pointers — Hare & Tortoise (Pattern 3)]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/fast-slow-pointers-hare-tortoise-pattern-3-8aba653d27af?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aba653d27af</guid>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 11:13:40 GMT</pubDate>
            <atom:updated>2025-10-02T11:13:40.556Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fast &amp; Slow Pointers — Hare &amp; Tortoise (Pattern 3)</h3><p>The Fast &amp; Slow pointer technique (aka <strong>Hare &amp; Tortoise</strong>) uses two pointers moving at different speeds through a sequence (array or linked list). It’s the canonical approach for detecting cycles and solving many linked-list problems in O(N) time and O(1) extra space.</p><p>This article explains the core idea, the common variants, and easy-to-follow solutions for the most important problems that use this pattern.</p><h3>Core idea</h3><p>Use two pointers that move at different rates (usually slow moves one step, fast moves two). In a cyclic structure the fast pointer will eventually catch up with the slow pointer. In an acyclic structure the fast pointer will reach the end.</p><p>Common uses:</p><ul><li>Detect if a cycle exists</li><li>Measure cycle length</li><li>Find the starting node of a cycle</li><li>Find the middle of a linked list</li><li>Reverse/compare half lists (palindrome check, reorder list)</li><li>Run pairwise/stepwise transforms without extra memory</li></ul><h3>Basic templates</h3><h3>Cycle detection (LinkedList)</h3><p>Move slow by 1 and fast by 2. If they ever become equal, a cycle exists. If fast hits null, there is no cycle.</p><pre>function hasCycle(head) {<br>  let slow = head, fast = head;<br>  while (fast !== null &amp;&amp; fast.next !== null) {<br>    slow = slow.next;<br>    fast = fast.next.next;<br>    if (slow === fast) return true;<br>  }<br>  return false;<br>}</pre><h3>Cycle length</h3><p>After slow === fast, fix one pointer and move the other until you return to the same node; count steps.</p><h3>Find cycle start</h3><ol><li>Detect cycle and compute its length K.</li><li>Set two pointers at head; advance pointer2 by K steps.</li><li>Move both pointers one step at a time — they meet at the cycle start.</li></ol><h3>Key problems &amp; intuition</h3><h3>LinkedList Cycle (easy)</h3><p>Detect presence of a cycle — use the basic detection template above. Time O(N), space O(1).</p><h3>Cycle length</h3><p>After detection, traverse the loop once to get its length. Useful input to find the cycle start.</p><h3>Start of cycle (LinkedList Cycle II, medium)</h3><p>Use cycle length to offset one pointer, then advance both until they meet — meeting point is the cycle entry.</p><h3>Happy Number (medium)</h3><p>The map of n -&gt; sum of squares of digits(n) eventually enters a cycle. Use fast/slow on the sequence of numbers to detect whether the cycle reaches 1 (happy) or some other loop (unhappy).</p><h3>Middle of the LinkedList (easy)</h3><p>Move fast by 2 and slow by 1 — when fast reaches the end, slow is at the middle (if even length, slow will be the second middle).</p><h3>Palindrome LinkedList (medium)</h3><ol><li>Find middle (fast/slow).</li><li>Reverse second half.</li><li>Compare first half and reversed second half.</li><li>Restore the list by reversing the second half again.<br>This uses O(1) extra space and O(N) time.</li></ol><h3>Reorder List (medium)</h3><p>Same initial steps as palindrome: find middle, reverse second half, then merge nodes alternately from first half and reversed second half.</p><h3>Cycle in a Circular Array (hard)</h3><p>Treat indices and jumps as a graph — to detect cycles that follow a single direction and have length &gt; 1, run a fast/slow procedure from each index, but stop early on direction changes or single-element loops. With memoization (marking visited indices) this can be improved from O(N^2) to O(N) at the cost of O(N) extra space.</p><h3>Patterns, pitfalls &amp; checklist</h3><ul><li><strong>When to use:</strong> sequences with repeated transitions (next pointers, index jumps, digit transforms) where cycles are possible.</li><li><strong>Detecting vs. locating:</strong> detection is cheaper; once detected you can compute cycle length or entry point using additional constant-time passes.</li><li><strong>Edge cases:</strong> empty list, single-node list, one-node self-loop, even/odd length lists, negative jumps in circular arrays (handle modulus carefully).</li><li><strong>Restoring state:</strong> when modifying structure (reverse second half), remember to undo changes if the original must be preserved.</li></ul><h3>Final tips</h3><ul><li>Fast &amp; Slow gives you cycle <em>insight</em> without extra memory — use it whenever the problem description suggests a repeating process.</li><li>Combine with other techniques (reverse list, two pointers, hashmap for memoization) depending on whether you need O(1) space or faster asymptotics.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aba653d27af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Pointers — clear patterns that simplify sorted-array & linked-list problems]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/two-pointers-clear-patterns-that-simplify-sorted-array-linked-list-problems-f8dfe1803ca7?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8dfe1803ca7</guid>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 11:04:59 GMT</pubDate>
            <atom:updated>2025-10-02T11:14:06.585Z</atom:updated>
            <content:encoded><![CDATA[<h3>Two Pointers — clear patterns that simplify sorted-array &amp; linked-list problems</h3><p>When the input is <em>sorted</em> (or you can sort it cheaply) — or when working with linked lists — the <strong>two pointers</strong> technique is a go-to approach. It lets you find pairs, triplets, or windows that satisfy constraints in linear time by moving two indices toward each other or in tandem.</p><p>This article explains the core ideas, shows short reusable templates, and walks through the most common problems with clear intuition and code snippets.</p><h3>Core idea</h3><p>Two pointers means maintaining two indices (or iterators): typically left and right. Depending on the problem you either:</p><ul><li>move them <strong>toward each other</strong> (left++ or right--) to find pairs that satisfy a condition, or</li><li>move one pointer forward while the other follows (common in linked-list problems), or</li><li>keep one pointer fixed and use the other to scan for a matching element.</li></ul><p>Because the input is sorted (or becomes sorted), comparisons let you decide which pointer to move without missing solutions.</p><h3>Simple templates</h3><h3>Pair with target sum (sorted array)</h3><pre>function pairWithTargetSum(arr, target) {<br>  let left = 0, right = arr.length - 1;<br>  while (left &lt; right) {<br>    const s = arr[left] + arr[right];<br>    if (s === target) return [left, right];<br>    if (s &lt; target) left++; else right--;<br>  }<br>  return [-1,-1];<br>}</pre><p>Time: O(N), Space: O(1).</p><h3>Two-pointer in linked-list: find middle, reverse, detect cycle</h3><ul><li>Finding middle: move fast by 2, slow by 1 — when fast hits end, slow is middle.</li><li>Reverse second half: standard iterative reverse using two pointers.</li><li>Cycle detection: Floyd’s tortoise &amp; hare (slow and fast).</li></ul><h3>Key problems (with intuition)</h3><h3>Remove duplicates from sorted array (in-place)</h3><p>Keep a write pointer for where the next unique value should go, and a read pointer to scan. When arr[read] differs from the last unique value, write it and advance write.</p><h3>Squares of a sorted array</h3><p>Because negatives can produce large squares, the largest square is at one of the ends. Use two pointers (left and right) and fill the result array from the end.</p><h3>Pair sum (unsorted) — hash table alternative</h3><p>If the array isn’t sorted or you need original indices quickly, use a hash map to check target - current. This costs O(N) time and O(N) space.</p><h3>Triplet sum to zero (3Sum)</h3><p>Sort the array, fix one number arr[i] and use two pointers to find pairs that sum to -arr[i]. Take care to skip duplicates to ensure uniqueness.</p><h3>Triplet sum closest to target</h3><p>Same approach as 3Sum but track the smallest absolute difference between currentSum and the target.</p><h3>Triplets with smaller sum (count)</h3><p>After sorting, for each i use two pointers left=i+1, right=n-1. If arr[left] + arr[right] &lt; target - arr[i], then ALL elements between leftand right paired with arr[left] will work — add right-left to the count and move left++.</p><h3>Subarrays with product less than K</h3><p>Use a sliding-window-like two-pointer strategy: expand the window multiplying by arr[right], and shrink from the left dividing by arr[left] while product ≥ K. For each right, the subarrays ending at right that qualify can be collected.</p><h3>Dutch National Flag / Sort Colors</h3><p>Keep three pointers: low, mid, high. Move through the array once and swap elements to partition into 0s, 1s, and 2s in O(N)time and O(1) space.</p><h3>4Sum (unique quadruplets)</h3><p>Sort and use two nested loops for the first two numbers; then apply two pointers for the remaining pair. Skip duplicates at every level.</p><h3>Backspace-string-compare</h3><p>Compare from the end with two pointers, skipping characters removed by # by counting backspaces as you move backwards.</p><h3>Minimum window sort (smallest subarray to sort)</h3><p>Find the first out-of-order element from left and right. Compute min/max of this candidate window and expand the window outward until the array outside the window is in correct order relative to these extremes.</p><h3>Practical tips &amp; checklist</h3><ol><li><strong>Sort if needed</strong> — if the problem allows sorting and costs are acceptable (often O(N log N)), sorting can open the two-pointer approach.</li><li><strong>Decide pointer movement by comparison</strong> — when sum is too big move right--, when too small move left++.</li><li><strong>Skip duplicates when asked for unique results</strong> — after finding a valid pair/triplet, advance pointers past equal values.</li><li><strong>For in-place transforms</strong>, maintain read/write pointers instead of allocating new arrays.</li><li><strong>For linked lists</strong>, replace indices with node pointers; patterns (middle, reverse, cycle) remain the same.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8dfe1803ca7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sliding Window — the simple pattern that solves many array & string problems]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/sliding-window-the-simple-pattern-that-solves-many-array-string-problems-be30dba7bb21?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/be30dba7bb21</guid>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 10:59:13 GMT</pubDate>
            <atom:updated>2025-10-02T11:14:31.898Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sliding Window — the simple pattern that solves many array &amp; string problems</h3><p>Sliding Window is one of those algorithmic patterns you should keep in your toolkit. It turns many brute-force O(N*K)solutions into clean O(N) implementations by <em>reusing</em> work as you move a window across the input.</p><p>This article explains the idea in plain language, shows short JavaScript templates, and walks through the most common problem-types with simple examples and intuition you can use right away.</p><h3>TL;DR</h3><ul><li>A <em>sliding window</em> is a contiguous region (subarray or substring) that moves left-to-right across the input.</li><li>Two main flavors:</li></ul><blockquote><strong>Fixed-size window</strong> — window length K is given. Slide and update in constant time.</blockquote><blockquote><strong>Variable-size window</strong> — expand until a condition holds, then shrink to improve the answer.</blockquote><ul><li>Most sliding-window problems run in O(N) time and O(1) or O(K) extra space.</li></ul><h3>The intuition</h3><p>If two consecutive windows overlap, you don’t need to recompute the overlap. Keep a running summary of the window (sum, frequency map, last index, etc.). When the window moves:</p><ul><li>Remove the left-most item that leaves.</li><li>Add the new right-most item that enters.</li></ul><p>For variable-size windows, expand the right side until your condition is met (e.g., sum ≥ S, or too many distinct chars), then move the left side forward until the condition is satisfied/violated the way you want.</p><h3>Fixed-size window template</h3><pre>function slidingFixed(arr, k) {<br>  const result = []<br>  let windowSum = 0<br>  let windowStart = 0<br><br>  for (let windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) {<br>    windowSum += arr[windowEnd]<br><br>    if (windowEnd &gt;= k - 1) {<br>      result.push(windowSum / k) // or record other metric<br>      windowSum -= arr[windowStart]<br>      windowStart++<br>    }<br>  }<br>  return result<br>}</pre><p>Use this when k is given and fixed (averages, fixed-length max sum, etc.).</p><h3>Variable-size window template</h3><pre>function slidingVariable(arr, conditionFn) {<br>  let windowStart = 0<br>  let windowState = /* e.g. sum or frequency map */<br>  let best = /* e.g. Infinity or 0 depending on problem */<br><br>  for (let windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) {<br>    // include arr[windowEnd]<br><br>    // shrink while condition satisfied (or violated depending on problem)<br>    while (/* shrink condition */) {<br>      // update best<br>      // remove arr[windowStart]<br>      windowStart++<br>    }<br>  }<br>  return best<br>}</pre><p>Use this for “smallest subarray with sum ≥ S”, “longest substring with ≤ K distinct chars”, etc.</p><h3>Common problems (short, plain explanations)</h3><h3>1) Averages of subarrays of size K (easy)</h3><p><strong>Idea:</strong> fixed window. Keep running sum, subtract leaving element, add entering element. O(N).</p><h3>2) Maximum sum subarray of size K (easy)</h3><p><strong>Idea:</strong> same as averages — track window sum and update max. O(N).</p><h3>3) Smallest subarray with sum ≥ S (easy)</h3><p><strong>Idea:</strong> variable window. Expand until sum ≥ S. Then shrink to find the minimal length. O(N).</p><h3>4) Longest substring with at most K distinct characters (medium)</h3><p><strong>Idea:</strong> variable window + frequency map. Expand until distinct &gt; K, then shrink until distinct ≤ K. Track max length. O(N)time, O(K) space.</p><h3>5) Longest substring without repeating characters (hard-ish)</h3><p><strong>Idea:</strong> keep last index map. When a repeat appears inside window, move windowStart to lastIndex + 1 (use max so you never move backward). Track max length.</p><h3>6) Longest repeating-character substring after ≤ K replacements</h3><p><strong>Idea:</strong> maintain char frequency and maxRepeatCount (the count of the most frequent char seen in the window). If (windowSize - maxRepeatCount) &gt; K, shrink. This avoids recomputing best-letter for every window.</p><h3>7) Permutation in a string / String anagrams</h3><p><strong>Idea:</strong> build frequency map of the pattern. Slide a window of pattern length and match frequencies. For anagrams, collect starting indices where all counts are matched.</p><h3>8) Minimum window substring (contains all pattern chars)</h3><p><strong>Idea:</strong> pattern-frequency map; expand until all required chars are matched, then shrink while maintaining the match to find the smallest window.</p><h3>9) Words concatenation (all words same length)</h3><p><strong>Idea:</strong> treat the string as chunks of wordLen. For each offset 0..wordLen-1, move in steps of wordLen and use a sliding idea with word-frequency maps to avoid re-parsing from every character.</p><h3>A small checklist to approach any sliding-window problem</h3><ol><li>Is the problem about contiguous subarrays/substrings? If no → sliding window probably not useful.</li><li>Is the window length fixed or flexible? Choose fixed or variable template accordingly.</li><li>What state do I need to keep? (sum, map of frequencies, lastIndex, maxRepeatCount, etc.)</li><li>When should I shrink the window? (when a condition is violated or when it becomes satisfied and you’re minimizing)</li><li>How often should I update the answer? (usually when your window meets the required condition)</li><li>Edge-cases: empty input, k greater than input length, negative numbers (they break some sum-based assumptions), unicode characters (counts), etc.</li></ol><h3>Final tips</h3><ul><li>Practice different variants: fixed-size, variable-size, char-count windows, and chunked windows for fixed-length words.</li><li>For strings, prefer arrays/maps for counts and track only what matters: distinct count, matched count, or last index.</li><li>Remember: the power of sliding window is reuse — don’t recompute overlap.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be30dba7bb21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Top 8 GitHub Repositories You Must Bookmark]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/my-top-8-github-repositories-you-must-bookmark-0da2b643af53?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/0da2b643af53</guid>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 10:53:31 GMT</pubDate>
            <atom:updated>2025-10-02T10:53:31.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top 8 GitHub Repositories You Must Bookmark</h3><p>These are the repos I return to again and again. Bookmark, star, fork — whatever helps you come back.</p><ul><li><a href="https://github.com/systemdesign42/system-design">system-design</a></li></ul><p>A collection of system design patterns, example architectures, and scalable system blueprints (microservices, caching, databases). Great when you want to internalize architecture tradeoffs.</p><ul><li><a href="https://github.com/yangshun/tech-interview-handbook">tech-interview-handbook</a></li></ul><p>A comprehensive guide to interviewing: data structures, algorithm patterns, behavioral tips, mock questions, and study plans.</p><ul><li><a href="https://github.com/jwasham/coding-interview-university">coding-interview-university</a></li></ul><p>A “computer science curriculum” built for coding interviews. If you treat this as your study syllabus, you’ll cover nearly everything from basics to advanced.</p><ul><li><a href="https://github.com/gregorojstersek/resources-to-become-a-great-engineering-leader">resources-to-become-a-great-engineering-leader</a></li></ul><p>For when your ambition outgrows “just coding.” This is a treasure trove of leadership books, articles, frameworks, and advice for growing as a technical leader.</p><ul><li><a href="https://github.com/EbookFoundation/free-programming-books">free-programming-books</a></li></ul><p>Exactly what it says — thousands of free books, tutorials, and resources across languages, frameworks, domains. Use this as your go-to catalog.</p><ul><li><a href="https://github.com/jordan-cutler/path-to-senior-engineer-handbook">path-to-senior-engineer-handbook</a></li></ul><p>A deliberate guide to thinking, communication, influence, ownership — all the soft and meta skills senior engineers need.</p><ul><li><a href="https://github.com/kamranahmedse/developer-roadmap">developer-roadmap</a></li></ul><p>A visual roadmap of skills &amp; technologies software engineers should pick up, whether frontend, backend, DevOps, etc.</p><ul><li><a href="https://github.com/freeCodeCamp/freeCodeCamp">freeCodeCamp</a></li></ul><p>One of the largest open communities in coding education. The curriculum, challenges, and community support are world class.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0da2b643af53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DSA Patterns: 2 Medium + 1 Hard Problems (with LeetCode Links)]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/dsa-patterns-2-medium-1-hard-problems-with-leetcode-links-48fe975ddca0?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/48fe975ddca0</guid>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 10:30:28 GMT</pubDate>
            <atom:updated>2025-10-02T10:30:56.145Z</atom:updated>
            <content:encoded><![CDATA[<p>Disclaimer: This roadmap assumes you already have a basic understanding of core DSA concepts</p><p>This article provides a <strong>focused roadmap</strong>: for each topic/pattern, solve <strong>2 medium + 1 hard problem</strong>. This way you cover both the typical interview-level problems and push your skills with one challenging variation.</p><h3>I. Two Pointer Patterns</h3><ul><li><strong>Converging Pointers</strong></li><li>Medium: <a href="https://leetcode.com/problems/3sum/">15. 3Sum</a>, <a href="https://leetcode.com/problems/3sum-closest/">16. 3Sum Closest</a></li><li>Hard: <a href="https://leetcode.com/problems/4sum/">18. 4Sum</a></li><li><strong>Fast &amp; Slow Pointers</strong></li><li>Medium: <a href="https://leetcode.com/problems/linked-list-cycle/">141. Linked List Cycle</a>, <a href="https://leetcode.com/problems/happy-number/">202. Happy Number</a></li><li>Hard: <a href="https://leetcode.com/problems/find-the-duplicate-number/">287. Find the Duplicate Number</a></li><li><strong>Fixed Separation</strong></li><li>Medium: <a href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">19. Remove Nth Node From End</a>, <a href="https://leetcode.com/problems/middle-of-the-linked-list/">876. Middle of the Linked List</a></li><li>Hard: <a href="https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/">2095. Delete the Middle Node of a Linked List</a></li><li><strong>In-place Array Modification</strong></li><li>Medium: <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/">26. Remove Duplicates from Sorted Array</a>, <a href="https://leetcode.com/problems/move-zeroes/">283. Move Zeroes</a></li><li>Hard: <a href="https://leetcode.com/problems/sort-colors/">75. Sort Colors</a></li><li><strong>Expanding from Center (Palindromes)</strong></li><li>Medium: <a href="https://leetcode.com/problems/palindromic-substrings/">647. Palindromic Substrings</a>, <a href="https://leetcode.com/problems/valid-palindrome-ii/">680. Valid Palindrome II</a></li><li>Hard: <a href="https://leetcode.com/problems/longest-palindromic-substring/">5. Longest Palindromic Substring</a></li></ul><h3>II. Sliding Window Patterns</h3><ul><li><strong>Fixed Size Window</strong></li><li>Medium: <a href="https://leetcode.com/problems/maximum-average-subarray-i/">643. Maximum Average Subarray I</a>, <a href="https://leetcode.com/problems/find-the-power-of-k-size-subarrays-i/">3254. Find the Power of K-Size Subarrays I</a></li><li>Hard: <a href="https://leetcode.com/problems/sliding-window-maximum/">239. Sliding Window Maximum</a></li><li><strong>Variable Size Window</strong></li><li>Medium: <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">3. Longest Substring Without Repeating Characters</a>, <a href="https://leetcode.com/problems/minimum-size-subarray-sum/">209. Minimum Size Subarray Sum</a></li><li>Hard: <a href="https://leetcode.com/problems/minimum-window-substring/">76. Minimum Window Substring</a></li><li><strong>Character Frequency Matching</strong></li><li>Medium: <a href="https://leetcode.com/problems/find-all-anagrams-in-a-string/">438. Find All Anagrams in a String</a>, <a href="https://leetcode.com/problems/permutation-in-string/">567. Permutation in String</a></li><li>Hard: <a href="https://leetcode.com/problems/substring-with-concatenation-of-all-words/">30. Substring with Concatenation of All Words</a></li></ul><h3>III. Tree Traversal Patterns</h3><ul><li><strong>BFS Traversals</strong></li><li>Medium: <a href="https://leetcode.com/problems/binary-tree-level-order-traversal/">102. Binary Tree Level Order Traversal</a>, <a href="https://leetcode.com/problems/binary-tree-right-side-view/">199. Binary Tree Right Side View</a></li><li>Hard: <a href="https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/">103. Binary Tree Zigzag Level Order Traversal</a></li><li><strong>DFS Traversals</strong></li><li>Medium: <a href="https://leetcode.com/problems/binary-tree-inorder-traversal/">94. Binary Tree Inorder Traversal</a>, <a href="https://leetcode.com/problems/binary-tree-paths/">257. Binary Tree Paths</a></li><li>Hard: <a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/">124. Binary Tree Maximum Path Sum</a></li><li><strong>Lowest Common Ancestor (LCA)</strong></li><li>Medium: <a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/">235. LCA of BST</a>, <a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/">236. LCA of Binary Tree</a></li><li>Hard: <a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/">1644. LCA of Binary Tree II</a></li></ul><h3>IV. Graph Traversal Patterns</h3><ul><li><strong>DFS/BFS Components</strong></li><li>Medium: <a href="https://leetcode.com/problems/number-of-islands/">200. Number of Islands</a>, <a href="https://leetcode.com/problems/max-area-of-island/">695. Max Area of Island</a></li><li>Hard: <a href="https://leetcode.com/problems/pacific-atlantic-water-flow/">417. Pacific Atlantic Water Flow</a></li><li><strong>Cycle Detection &amp; Topological Sort</strong></li><li>Medium: <a href="https://leetcode.com/problems/course-schedule/">207. Course Schedule</a>, <a href="https://leetcode.com/problems/course-schedule-ii/">210. Course Schedule II</a></li><li>Hard: <a href="https://leetcode.com/problems/alien-dictionary/">269. Alien Dictionary</a></li><li><strong>Shortest Path</strong></li><li>Medium: <a href="https://leetcode.com/problems/network-delay-time/">743. Network Delay Time</a>, <a href="https://leetcode.com/problems/path-with-minimum-effort/">1631. Path With Minimum Effort</a></li><li>Hard: <a href="https://leetcode.com/problems/swim-in-rising-water/">778. Swim in Rising Water</a></li></ul><h3>V. Dynamic Programming (DP)</h3><ul><li><strong>1D DP (Classic)</strong></li><li>Medium: <a href="https://leetcode.com/problems/house-robber/">198. House Robber</a>, <a href="https://leetcode.com/problems/house-robber-ii/">213. House Robber II</a></li><li>Hard: <a href="https://leetcode.com/problems/house-robber-iii/">337. House Robber III</a></li><li><strong>Kadane’s Algorithm</strong></li><li>Medium: <a href="https://leetcode.com/problems/maximum-subarray/">53. Maximum Subarray</a>, <a href="https://leetcode.com/problems/maximum-sum-circular-subarray/">918. Maximum Sum Circular Subarray</a></li><li>Hard: <a href="https://leetcode.com/problems/maximum-product-subarray/">152. Maximum Product Subarray</a></li><li><strong>Knapsack Variants</strong></li><li>Medium: <a href="https://leetcode.com/problems/partition-equal-subset-sum/">416. Partition Equal Subset Sum</a>, <a href="https://leetcode.com/problems/target-sum/">494. Target Sum</a></li><li>Hard: <a href="https://leetcode.com/problems/profitable-schemes/">879. Profitable Schemes</a></li><li><strong>LCS &amp; String DP</strong></li><li>Medium: <a href="https://leetcode.com/problems/longest-common-subsequence/">1143. Longest Common Subsequence</a>, <a href="https://leetcode.com/problems/edit-distance/">72. Edit Distance</a></li><li>Hard: <a href="https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/">1312. Minimum Insertion Steps to Make a String Palindrome</a></li></ul><h3>VI. Backtracking Patterns</h3><ul><li><strong>Subsets &amp; Permutations</strong></li><li>Medium: <a href="https://leetcode.com/problems/subsets/">78. Subsets</a>, <a href="https://leetcode.com/problems/permutations/">46. Permutations</a></li><li>Hard: <a href="https://leetcode.com/problems/n-queens/">51. N-Queens</a></li><li><strong>Combination Problems</strong></li><li>Medium: <a href="https://leetcode.com/problems/combination-sum/">39. Combination Sum</a>, <a href="https://leetcode.com/problems/combination-sum-ii/">40. Combination Sum II</a></li><li>Hard: <a href="https://leetcode.com/problems/remove-invalid-parentheses/">301. Remove Invalid Parentheses</a></li></ul><h3>VII. Greedy Patterns</h3><ul><li><strong>Intervals</strong></li><li>Medium: <a href="https://leetcode.com/problems/merge-intervals/">56. Merge Intervals</a>, <a href="https://leetcode.com/problems/insert-interval/">57. Insert Interval</a></li><li>Hard: <a href="https://leetcode.com/problems/employee-free-time/">759. Employee Free Time</a></li><li><strong>Jump Game</strong></li><li>Medium: <a href="https://leetcode.com/problems/jump-game/">55. Jump Game</a>, <a href="https://leetcode.com/problems/gas-station/">134. Gas Station</a></li><li>Hard: <a href="https://leetcode.com/problems/jump-game-ii/">45. Jump Game II</a></li></ul><h3>VIII. Binary Search Patterns</h3><ul><li><strong>Classic Binary Search</strong></li><li>Medium: <a href="https://leetcode.com/problems/search-a-2d-matrix/">74. Search a 2D Matrix</a>, <a href="https://leetcode.com/problems/single-element-in-a-sorted-array/">540. Single Element in a Sorted Array</a></li><li>Hard: <a href="https://leetcode.com/problems/median-of-two-sorted-arrays/">4. Median of Two Sorted Arrays</a></li><li><strong>Binary Search on Answer</strong></li><li>Medium: <a href="https://leetcode.com/problems/koko-eating-bananas/">875. Koko Eating Bananas</a>, <a href="https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/">1011. Capacity To Ship Packages</a></li><li>Hard: <a href="https://leetcode.com/problems/split-array-largest-sum/">410. Split Array Largest Sum</a></li></ul><p>✅ With this roadmap (2 medium + 1 hard per subtopic), you will cover <strong>depth + variation</strong> efficiently, preparing you for both mid-level and tough interview challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48fe975ddca0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DSA Patterns & Practice — Coding Interview Series]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/dsa-patterns-practice-coding-interview-series-b15a7bc02871?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/b15a7bc02871</guid>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 10:20:01 GMT</pubDate>
            <atom:updated>2025-10-02T10:20:01.333Z</atom:updated>
            <content:encoded><![CDATA[<h3>DSA Patterns &amp; Practice — Coding Interview Series</h3><p>When preparing for coding interviews, the biggest challenge is not just solving problems — it’s recognizing the <em>pattern </em>behind them. Once you master patterns, you can unlock solutions for hundreds of problems by learning just a few key ideas.</p><p>This guide organizes popular problems into patterns — grouped by technique (two pointers, sliding window, DFS, BFS, DP, etc.) — so you can focus on the <em>approach</em> rather than memorizing individual solutions.</p><h3>🔑 Pro Tip</h3><p>You don’t need to solve <em>all</em> problems. Instead, aim for <strong>1 medium + 1 hard problem per pattern</strong>. Once you deeply understand the core logic, most variations will become intuitive.</p><h3>I. Two Pointer Patterns</h3><ul><li><strong>Converging Pointers:</strong> e.g., 3Sum, Container With Most Water</li><li><strong>Fast &amp; Slow Pointers:</strong> e.g., Linked List Cycle, Happy Number</li><li><strong>Fixed Separation:</strong> e.g., Remove Nth Node From End</li><li><strong>In-place Array Modifications:</strong> e.g., Remove Duplicates, Move Zeroes</li><li><strong>String Comparison with Backspaces:</strong> e.g., Backspace String Compare</li><li><strong>Expanding from Center (Palindromes):</strong> e.g., Longest Palindromic Substring</li><li><strong>String Reversal:</strong> e.g., Reverse Words in a String</li></ul><h3>II. Sliding Window Patterns</h3><ul><li><strong>Fixed Size Windows:</strong> e.g., Moving Average, Maximum Average Subarray</li><li><strong>Variable Size Windows:</strong> e.g., Longest Substring Without Repeating Characters, Minimum Window Substring</li><li><strong>Monotonic Queue:</strong> e.g., Sliding Window Maximum</li><li><strong>Character Frequency Matching:</strong> e.g., Find All Anagrams in a String</li></ul><h3>III. Tree Traversal Patterns</h3><ul><li><strong>BFS:</strong> Level Order, Zigzag, Right View</li><li><strong>DFS:</strong> Preorder, Inorder, Postorder, Path Sum problems</li><li><strong>Lowest Common Ancestor (LCA):</strong> BST and general trees</li><li><strong>Serialization &amp; Deserialization:</strong> Reconstructing trees from strings</li></ul><h3>IV. Graph Traversal Patterns</h3><ul><li><strong>DFS &amp; BFS:</strong> Islands, Rotting Oranges, Shortest Path in Binary Matrix</li><li><strong>Cycle Detection &amp; Topological Sort:</strong> Course Schedule, Alien Dictionary</li><li><strong>Graph Cloning &amp; Shortest Paths:</strong> Clone Graph, Dijkstra, Bellman-Ford</li><li><strong>Union-Find &amp; MST:</strong> Redundant Connection, Kruskal/Prim</li><li><strong>Advanced:</strong> Tarjan’s Algorithm (SCC, Bridges)</li></ul><h3>V. Dynamic Programming (DP) Patterns</h3><ul><li><strong>1D DP:</strong> Fibonacci, Kadane’s Algorithm, Coin Change, Knapsack, Word Break</li><li><strong>2D DP:</strong> LCS, Edit Distance, Unique Paths, Interval DP</li><li><strong>LIS &amp; Stock Problems:</strong> Classic interview favorites</li><li><strong>Catalan Numbers:</strong> Unique BSTs, Parentheses</li></ul><h3>VI. Heap (Priority Queue) Patterns</h3><ul><li><strong>Top-K Elements:</strong> Kth Largest, Top K Frequent</li><li><strong>Two Heaps for Median:</strong> Median of Data Stream</li><li><strong>K-way Merge:</strong> Merge k Sorted Lists</li><li><strong>Scheduling/Greedy:</strong> Meeting Rooms, Furthest Building</li></ul><h3>VII. Backtracking Patterns</h3><ul><li><strong>Subsets &amp; Permutations:</strong> Classic recursion</li><li><strong>Combination Sum &amp; Parentheses Generation</strong></li><li><strong>Word Search &amp; N-Queens</strong></li><li><strong>Palindrome Partitioning</strong></li></ul><h3>VIII. Greedy Patterns</h3><ul><li><strong>Intervals:</strong> Merge, Insert, Employee Free Time</li><li><strong>Jump Game, Gas Station, Stock Buy/Sell</strong></li><li><strong>Task Scheduling, Sorting-Based Greedy</strong></li></ul><h3>IX. Binary Search Patterns</h3><ul><li><strong>On Sorted Arrays:</strong> Search, Sqrt, Rotated Array</li><li><strong>Binary Search on Answer:</strong> Min Days to Make Bouquets, Koko Eating Bananas</li><li><strong>First/Last Occurrence, Median of Two Sorted Arrays</strong></li></ul><h3>X. Stack Patterns</h3><ul><li><strong>Parentheses Matching:</strong> Valid Parentheses, Longest Valid Parentheses</li><li><strong>Monotonic Stack:</strong> Next Greater Element, Daily Temperatures</li><li><strong>Expression Evaluation:</strong> Reverse Polish Notation, Basic Calculator</li><li><strong>Histogram Problems:</strong> Largest Rectangle, Maximal Rectangle</li></ul><h3>XI. Bit Manipulation Patterns</h3><ul><li><strong>XOR tricks:</strong> Single Number, Missing Number</li><li><strong>Set Bits &amp; Power of Two</strong></li><li><strong>Bitwise DP optimizations</strong></li></ul><h3>XII. Linked List Patterns</h3><ul><li><strong>Reversal:</strong> Reverse Linked List, Reverse in k-Group, Palindrome Linked List</li><li><strong>Merging, Addition, Intersection, Reordering</strong></li></ul><h3>XIII. Array &amp; Matrix Patterns</h3><ul><li><strong>Rotation, Spiral Traversal, Set Matrix Zeroes</strong></li><li><strong>Prefix/Suffix Products, Cyclic Sort</strong></li><li><strong>In-place Merge, Carry Handling (Plus One)</strong></li></ul><h3>XIV. String Patterns</h3><ul><li><strong>Palindrome Check, Anagram Grouping</strong></li><li><strong>String to Integer, Roman Conversion</strong></li><li><strong>String Matching (KMP/Rabin-Karp)</strong></li><li><strong>Repeated Substring Patterns</strong></li></ul><h3>XV. Design &amp; Trie Patterns</h3><ul><li><strong>Design Problems:</strong> LRU Cache, Min Stack, Snake Game, Autocomplete System</li><li><strong>Trie-Based:</strong> Word Dictionary, Replace Words, Word Squares</li></ul><h3>🚀 How to Use This Roadmap</h3><ol><li>Pick a pattern (e.g., Sliding Window).</li><li>Solve <strong>1 medium + 1 hard</strong> problem.</li><li>Review variations and note what changes in constraints/logic.</li><li>Move to the next pattern.</li></ol><p>In 2–3 months, you’ll not only cover all core DSA topics but also develop strong pattern recognition — the real key to cracking interviews.</p><p>✅ Save this roadmap.<br>✅ Practice by patterns.<br>✅ Master interviews faster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b15a7bc02871" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 457. Circular Array Loop]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/leetcode-457-circular-array-loop-fdcec9ea5746?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdcec9ea5746</guid>
            <category><![CDATA[floyd-cycle-detection]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[hare-and-tortoise]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 09:02:13 GMT</pubDate>
            <atom:updated>2020-04-20T09:02:13.270Z</atom:updated>
            <content:encoded><![CDATA[<p>You are given a <strong>circular</strong> array nums of positive and negative integers. If a number <em>k</em> at an index is positive, then move forward <em>k</em> steps. Conversely, if it&#39;s negative (-<em>k</em>), move backward <em>k</em> steps. Since the array is circular, you may assume that the last element&#39;s next element is the first element, and the first element&#39;s previous element is the last element.</p><p>Determine if there is a loop (or a cycle) in nums. A cycle must start and end at the same index and the cycle&#39;s length &gt; 1. Furthermore, movements in a cycle must all follow a single direction. In other words, a cycle must not consist of both forward and backward movements.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong> [2,-1,1,2,2]<br><strong>Output:</strong> true<br><strong>Explanation:</strong> There is a cycle, from index 0 -&gt; 2 -&gt; 3 -&gt; 0. The cycle&#39;s length is 3.</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> [-1,2]<br><strong>Output:</strong> false<br><strong>Explanation:</strong> The movement from index 1 -&gt; 1 -&gt; 1 ... is not a cycle, because the cycle&#39;s length is 1. By definition the cycle&#39;s length must be greater than 1.</pre><p><strong>Example 3:</strong></p><pre><strong>Input:</strong> [-2,1,-1,-2,-2]<br><strong>Output:</strong> false<br><strong>Explanation:</strong> The movement from index 1 -&gt; 2 -&gt; 1 -&gt; ... is not a cycle, because movement from index 1 -&gt; 2 is a forward movement, but movement from index 2 -&gt; 1 is a backward movement. All movements in a cycle must follow a single direction.</pre><p><strong>Note:</strong></p><ol><li>-1000 ≤ nums[i] ≤ 1000</li><li>nums[i] ≠ 0</li><li>1 ≤ nums.length ≤ 5000</li></ol><p><strong>Follow up:</strong></p><p>Could you solve it in <strong>O(n)</strong> time complexity and <strong>O(1)</strong> extra space complexity?</p><p>I would like to share my approach.<br><strong>457. Circular Array Loop</strong><br>As the name suggests we have to find a loop that exists in the array, but the <strong>loop exists</strong> in <strong>two directions</strong> i.e., either in <strong>left-to-right</strong> or <strong>right-to-left</strong> direction.</p><p>Well, we know there is one common algorithm to test whether a LinkedList / Array contains a loop or not.</p><p>Slow &amp; Fast pointer or Hare &amp; Tortoise or Floyd&#39;s cylce detection,<br>for more details <a href="https://en.wikipedia.org/wiki/Cycle_detection#Floyd&#39;s_Tortoise_and_Hare">Click here</a></p><p>Our code starts with as usual like checking for loop in the linked list.</p><pre>/// linked list template<br>... <br>while(fast &amp;&amp; fast-&gt;next){ <br>	/// both go in one direction, for this case left-to-right<br>	slow = slow-&gt;next;<br>	fast = fast-&gt;next-&gt;next;<br>	if(slow == fast){<br>		/// loop exists<br>	}<br>}<br>...</pre><p>Now we got a glimpse of slow &amp; fast pointer.<br><strong>Note:</strong> loop exists in both directions, we have to check this as well in while loop condition.<br><strong>Condition:</strong><br>nums[slow]*nums[next(nums,fast)]&gt;0 &amp;&amp; nums[slow]*nums[next(nums,next(nums,fast))]&gt;0</p><p>See below code (Incomplete):</p><pre>...<br>/// the condition for both direction<br>while(nums[slow]*nums[next(nums,fast)]&gt;0 &amp;&amp; nums[slow]*nums[next(nums,next(nums,fast))]&gt;0){<br>	slow = next(nums,slow);<br>	fast = next(nums,next(nums,fast));int next(vector&lt;int&gt;&amp; nums, int i){<br>        int n = nums.size();<br>        return (n+nums[i]+i)%n;<br>    }<br>	if(slow==fast){<br>		if(slow==next(nums,slow)) // single length<br>			return false;<br>		return true;<br>	}<br>}<br>...</pre><p><strong>Note</strong> above next(nums, i) is defined as (n + nums[i] + i)%n. Here n is added extra to handle negative numbers (nums[i]).</p><p>Now complete code is below, with some pre-processing of input array element, to handle cases<br>like,<br>lengthOfArray = 4, and nums[i] = -9<br>OR<br>lengthOfArray = 4, and nums[i] = 12<br>Note: values are random.</p><p>Now <strong>COMPLETE CODE:</strong></p><pre>class Solution {<br>public:<br>    <br>    int next(vector&lt;int&gt;&amp; nums, int i){<br>        int n = nums.size();<br>        return (n+nums[i]+i)%n;<br>    }<br>    <br>    bool circularArrayLoop(vector&lt;int&gt;&amp; nums) {<br>        int n = nums.size();<br>        // we can use slow and fast pointer to check whether there is loop or not<br>        for(int &amp;num: nums)<br>            num %= n;<br>        for(int i=0;i&lt;n;i++){<br>            int slow = i,<br>                fast = i;<br>            while(nums[slow]*nums[next(nums,fast)]&gt;0 &amp;&amp; nums[slow]*nums[next(nums,next(nums,fast))]&gt;0){<br>                slow = next(nums,slow);<br>                fast = next(nums,next(nums,fast));<br>                if(slow==fast){<br>                    if(slow==next(nums,slow)) // single length<br>                        return false;<br>                    return true;<br>                }<br>            }<br>			/// DONOT TRAVERSE WHERE THERE IS NO PATH TO GET LOOP.<br>            int j = i;<br>            int val = nums[i];<br>            while (nums[j] * val &gt; 0) {<br>                int nexx = next(nums,j);<br>                nums[j] = 0;<br>                j = nexx;<br>            }<br>        }<br>        <br>        return false;<br>    }<br>};</pre><p><strong>Note:</strong> Please pardon my English.<br>Thank you!</p><p>my leetcode id: <strong>trade_off</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdcec9ea5746" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 1048. Longest String Chain]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/leetcode-1048-longest-string-chain-32a6385f974e?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/32a6385f974e</guid>
            <category><![CDATA[ds-algo]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[pd]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 08:58:09 GMT</pubDate>
            <atom:updated>2020-04-20T08:58:09.000Z</atom:updated>
            <content:encoded><![CDATA[<p>Given a list of words, each word consists of English lowercase letters.</p><p>Let’s say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, &quot;abc&quot; is a predecessor of &quot;abac&quot;.</p><p>A <em>word chain </em>is a sequence of words [word_1, word_2, ..., word_k] with k &gt;= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.</p><p>Return the longest possible length of a word chain with words chosen from the given list of words.</p><p><strong>Example 1:</strong></p><pre><strong>Input: </strong>[&quot;a&quot;,&quot;b&quot;,&quot;ba&quot;,&quot;bca&quot;,&quot;bda&quot;,&quot;bdca&quot;]<br><strong>Output: </strong>4<br><strong>Explanation</strong>: one of the longest word chain is &quot;a&quot;,&quot;ba&quot;,&quot;bda&quot;,&quot;bdca&quot;.</pre><p><strong>Note:</strong></p><ol><li>1 &lt;= words.length &lt;= 1000</li><li>1 &lt;= words[i].length &lt;= 16</li><li>words[i] only consists of English lowercase letters.</li></ol><p>This is Dynamic Programming Question.</p><p>Why?</p><p>Because we have so many choices but we want an optimal solution.</p><p>In such scenarios, we can use DP to help us.</p><pre>class Solution {<br>public:<br>    int longestStrChain(vector&lt;string&gt;&amp; words) {<br>        /// dp[i] = longest chain of words till i-th index<br>        sort(words.begin(), words.end(), [](string a, string b){<br>            return a.size() &lt; b.size();<br>        }); /// why sort?, because, we want to solve it for smaller subproblems first<br>        unordered_map&lt;string, int&gt; dict;<br>        for(int i=0;i&lt;words.size();i++)<br>                dict[words[i]] = i;<br>        vector&lt;int&gt; dp(words.size(), 1);<br>        int max_ = 0;<br>        for(int j=0;j&lt;words.size();j++){<br>            string word = words[j];<br>            for(int k=0;k&lt;word.size();k++){<br>                string nword = word.substr(0, k) + word.substr(k+1);<br>                if(dict.count(nword)){<br>                    int z = dict[nword];<br>                    if(dp[j] &lt; 1 + dp[z]){<br>                        dp[j] = 1 + dp[z];<br>                    }<br>                }<br>            }<br>            max_ = max(max_, dp[j]);<br>        }<br>        return max_;<br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32a6385f974e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 215. Kth Largest Element in an Array]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/leetcode-215-kth-largest-element-in-an-array-b017558e13a8?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/b017558e13a8</guid>
            <category><![CDATA[order-statistics]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 08:52:01 GMT</pubDate>
            <atom:updated>2020-04-20T08:52:01.204Z</atom:updated>
            <content:encoded><![CDATA[<p>Find the <strong>k</strong>th largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.</p><p><strong>Example 1:</strong></p><pre><strong>Input:</strong> [3,2,1,5,6,4] and k = 2<br><strong>Output:</strong> 5</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> [3,2,3,1,2,4,5,5,6] and k = 4<br><strong>Output:</strong> 4</pre><p><strong>Note:</strong><br>You may assume k is always valid, 1 ≤ k ≤ array’s length.</p><p><strong>Intuition</strong>: Say we found the Kth Largest element, then we can say that<br>in a sorted array, on the right of this element there is K-1 element which is greater than it and left there is N-K elements smaller. Can we not use Binary search if we have search space between min_element and max_element?<br>where N is the size of the array.</p><p>Yes, Binary Search can help us here. Since for binary search, we need a set where half things can be neglected by some condition so that we can reach the best solution possible.</p><pre>class Solution {<br>public:<br>   <br>    int findKthLargest(vector&lt;int&gt;&amp; A, int k) {<br>        int lo = *min_element(A.begin(), A.end()),<br>            hi = *max_element(A.begin(), A.end());<br>        int m = A.size();<br>        while(lo&lt;hi){<br>            int mid = lo+(hi-lo)/2;<br>            /// now check how many elements are lesser than mid<br>            int count = 0;<br>            for(int i=0;i&lt;m;i++){<br>                count += (A[i]&lt;=mid);<br>            }</pre><pre>            if(count &lt; m-k+1) lo = mid+1; /// mid is also included<br>            else hi = mid;<br>        }<br>        return lo;<br>    }<br>};</pre><p>Note: If you have some other approach please share. My leetcode id is <strong>trade_off</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b017558e13a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knapsack (repetition allowed/not allowed) (Dynamic Programming)]]></title>
            <link>https://medium.com/@mithlesh.kumar.4257/knapsack-repetition-allowed-not-allowed-dynamic-programming-3adae7b7c412?source=rss-55461a58e178------2</link>
            <guid isPermaLink="false">https://medium.com/p/3adae7b7c412</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[pd]]></category>
            <category><![CDATA[knapsack-problem]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Mithlesh Kumar]]></dc:creator>
            <pubDate>Thu, 15 Aug 2019 13:10:08 GMT</pubDate>
            <atom:updated>2019-08-15T13:10:08.974Z</atom:updated>
            <content:encoded><![CDATA[<p>[GeeksForGeeks Practice]</p><p><strong>Q1. </strong>Given <strong>weights </strong>and <strong>values </strong>related to<strong> n</strong> items and the maximum capacity allowed for these items. What is the maximum value we can achieve if we can pick any weights any number of times for a total allowed weight of <strong>W</strong>?</p><p><strong>Input:</strong><br>The first line of input contains an integer denoting the number of test cases. Then T test cases follow. Each test case contains two integers N and W denoting the number of items and the total allowed <strong>weight</strong>. In the next two lines are space-separated values of the array denoting values of the items (val[]) and their weights (wt[]) respectively.</p><p><strong>Output:</strong><br>For each test case, in a new line, print the maximum value which we can achieve if we can pick any weights any number of times for a bag of size <strong>W</strong>.</p><p><strong>Constraints:</strong><br>1 &lt;= T &lt;= 100<br>1 &lt;= N, W &lt;= 103<br>1 &lt;= wt[], val[] &lt;= 100</p><p><strong>Example:<br>Input:</strong><br>2<br>2 3<br>1 1<br>2 1 <br>4 8<br>1 4 5 7<br>1 3 4 5<br><strong>Output:</strong><br>3<br>11</p><p>Solution</p><p><a href="https://raw.githubusercontent.com/mithlesh425/CodingInterview/master/Coding%20Interview%202019/knapsack01.cpp"><strong>https://raw.githubusercontent.com/mithlesh425/CodingInterview/master/Coding%20Interview%202019/knapsack01.cpp</strong></a></p><p><strong>Q2.</strong>You are given weights and values of <strong>N</strong> items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only <strong>one quantity of each item</strong>.<br>In other words, given two integer arrays <strong>val[0..N-1]</strong> and <strong>wt[0..N-1]</strong> which represent values and weights associated with <strong>N</strong> items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of <strong>val[]</strong> such that sum of the weights of this subset is smaller than or equal to <strong>W.</strong> You cannot break an item, <strong>either pick the complete item, or don’t pick it (0–1 property)</strong>.</p><p><strong>Input:</strong><br>The first line of input contains an integer <strong>T</strong> denoting the number of test cases. Then <strong>T</strong>test cases follow. Each test case consists of four lines.<br>The first line consists of <strong>N</strong> the number of items.<br>The second line consists of <strong>W</strong>, the maximum capacity of the knapsack.<br>In the next line are <strong>N</strong> space separated positive integers denoting the values of the <strong>N</strong>items,<br>and in the fourth line are <strong>N</strong> space separated positive integers denoting the weights of the corresponding items.</p><p><strong>Output:</strong><br>For each testcase, in a new line, print the <strong>maximum possible</strong> value you can get with the given conditions that you can obtain for each test case in a new line.</p><p><strong>Constraints:</strong><br>1 ≤ T ≤ 100<br>1 ≤ N ≤ 1000<br>1 ≤ W ≤ 1000<br>1 ≤ wt[i] ≤ 1000<br>1 ≤ v[i] ≤ 1000</p><p><strong>Example:</strong><br><strong>Input:</strong><br>2<br>3<br>4<br>1 2 3<br>4 5 1<br>2<br>3<br>1 2 3<br>4 5 6<br><strong>Output:</strong><br>3<br>1</p><p>Solution:</p><p><a href="https://raw.githubusercontent.com/mithlesh425/CodingInterview/master/Coding%20Interview%202019/knapsack01.cpp">https://raw.githubusercontent.com/mithlesh425/CodingInterview/master/Coding%20Interview%202019/knapsack01.cpp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3adae7b7c412" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>