{"id":121511,"date":"2026-07-08T17:52:32","date_gmt":"2026-07-08T12:22:32","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=121511"},"modified":"2026-07-08T17:52:35","modified_gmt":"2026-07-08T12:22:35","slug":"sliding-window-technique-explained","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/sliding-window-technique-explained\/","title":{"rendered":"Sliding Window Technique: Explained with Examples"},"content":{"rendered":"\n<p>If you&#8217;ve ever solved an array or string problem using two nested loops and wondered whether there&#8217;s a smarter way, there is, and it&#8217;s called the &#8220;sliding window&#8221; technique. It&#8217;s one of the most practical and frequently tested patterns in coding interviews, and once you understand how it works, you&#8217;ll start spotting it in problems you&#8217;ve struggled with before.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>TL;DR Summary\u00a0<\/strong><\/h2>\n\n\n\n<ol>\n<li>Idea: keep a window [l,r], update result by adding incoming and removing outgoing&nbsp; turns many O(n\u00b2) checks into O(n).<\/li>\n\n\n\n<li>Types: fixed-size (k, shift one; e.g., max k-sum) and variable-size (expand\/contract by condition; e.g., \u2264k distinct, min subarray \u2265 target).<\/li>\n\n\n\n<li>Pattern: two pointers + running state (sum or freq map), O(1) updates; spot contiguous-range problems (longest\/shortest\/max\/min\/count).<\/li>\n<\/ol>\n\n\n\n<p><em>To learn more about the sliding window technique and how it turns nested loops into O(n) solutions. Master this and more DSA patterns in HCL GUVI\u2019s <\/em><a href=\"https:\/\/www.guvi.in\/courses\/bundles\/dsa-for-programmers\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong><em>DSA for Programmers<\/em><\/strong><\/a><em>.<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What Is the Sliding Window Technique?<\/strong><\/h2>\n\n\n\n<p>The sliding window technique solves subarray and substring problems by maintaining a moving range of elements, a &#8220;window,&#8221; that slides through the data one step at a time. Instead of recalculating everything from scratch at each step, it reuses the previous result, reducing time complexity from O(n\u00b2) to O(n).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>The Problem With Brute Force<\/strong><\/h2>\n\n\n\n<ul>\n<li>Imagine you have an array and you need to find the maximum sum of any subarray of size k. The brute-force way is to loop through every possible starting index and sum the next k elements from there. That works, but it&#8217;s O(n \u00d7 k) slow when the array is large.<\/li>\n\n\n\n<li>The issue is repetition. Every time you move one step forward, you&#8217;re re-summing k elements that mostly overlap with the previous window. You&#8217;re reprocessing elements you&#8217;ve already seen. The sliding window technique eliminates that redundancy.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How the Sliding Window Works<\/strong><\/h2>\n\n\n\n<ul>\n<li>The core idea is simple: instead of recalculating the entire window sum from scratch, just subtract the element leaving the window and add the element entering it.<\/li>\n\n\n\n<li>Here&#8217;s a concrete example. Given arr = [5, 2, -1, 0, 3] and k = 3:<\/li>\n\n\n\n<li>First, compute the sum of the initial window: 5 + 2 + (-1) = 6. That&#8217;s your starting sum.<\/li>\n\n\n\n<li>Now slide the window one step right. Drop 5 (the leftmost element), add 0 (the new rightmost element): 6 &#8211; 5 + 0 = 1. New window sum: 1.<\/li>\n\n\n\n<li>Slide again. Drop 2, add 3: 1 &#8211; 2 + 3 = 2. New window sum: 2.<\/li>\n\n\n\n<li>Track the maximum across all windows&nbsp; it&#8217;s 6, from the first window [5, 2, -1].<\/li>\n\n\n\n<li>Each element is visited exactly once. Time complexity: O(n). Space complexity: O(1). That&#8217;s the power of this approach.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Fixed vs. Variable-Size Windows<\/strong><\/h2>\n\n\n\n<p>There are two types of sliding windows, and knowing which one to use is the key to solving different problem categories.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Feature<\/strong><\/td><td><strong>Fixed Size Window<\/strong><\/td><td><strong>Variable Size Window<\/strong><\/td><\/tr><tr><td>Window size<\/td><td>Set before you start (given as k)<\/td><td>Grows and shrinks dynamically<\/td><\/tr><tr><td>Pointer movement<\/td><td>The right pointer moves; left follows by 1<\/td><td>The left pointer moves only when the condition breaks<\/td><\/tr><tr><td>Use case<\/td><td>Max\/min sum of subarray of size k<\/td><td>Longest\/smallest subarray meeting a condition<\/td><\/tr><tr><td>Complexity<\/td><td>O(n)<\/td><td>O(n)<\/td><\/tr><tr><td>Example problems<\/td><td>Max sum subarray of size k<\/td><td>Longest substring with k distinct characters<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<ol>\n<li><strong>Fixed-size window<\/strong> problems give you the window size up front. You compute the first window, then slide one step at a time, adding the new element and dropping the old one.<\/li>\n\n\n\n<li><strong>Variable-size window<\/strong> problems don&#8217;t give you a fixed size. You expand the right pointer when the condition holds and shrink from the left when it breaks. The window grows and contracts until you find the optimal answer.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Fixed Window Example: Maximum Sum Subarray of Size K<\/strong><\/h2>\n\n\n\n<p>This is the most common entry-level sliding window problem.<\/p>\n\n\n\n<p><strong>Problem:<\/strong> Given arr = [1, 4, 2, 10, 23, 3, 1, 0, 20] and k = 4, find the maximum sum of any subarray of size 4.<\/p>\n\n\n\n<p><strong>Step 1:<\/strong> Compute the first window sum: 1 + 4 + 2 + 10 = 17. Set max_sum = 17.<\/p>\n\n\n\n<p><strong>Step 2:<\/strong> Slide the window. window_sum = 17 &#8211; 1 + 23 = 39. Update max_sum = 39.<\/p>\n\n\n\n<p><strong>Step 3:<\/strong> Slide again. window_sum = 39 &#8211; 4 + 3 = 38. max_sum stays 39.<\/p>\n\n\n\n<p><strong>Step 4:<\/strong> window_sum = 38 &#8211; 2 + 1 = 37. max_sum stays 39.<\/p>\n\n\n\n<p>Continue until the end. The answer is 39, from the subarray [4, 2, 10, 23].<\/p>\n\n\n\n<p>Here&#8217;s the <a href=\"https:\/\/www.guvi.in\/blog\/reasons-why-you-should-learn-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python <\/a>code for this:<\/p>\n\n\n\n<p>def max_sum_subarray(arr, k): n = len(arr) window_sum = sum(arr[:k]) max_sum = window_sum for i in range(n &#8211; k): window_sum = window_sum &#8211; arr[i] + arr[i + k] max_sum = max(max_sum, window_sum) return max_sum<\/p>\n\n\n\n<p>Clean, readable, and runs in O(n). No nested loops needed.<\/p>\n\n\n\n<div style=\"background-color: #099f4e; border: 3px solid #110053; border-radius: 12px; padding: 18px 22px; color: #FFFFFF; font-size: 18px; font-family: Montserrat, Helvetica, sans-serif; line-height: 1.6; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); max-width: 750px;\">\n\n  <strong style=\"font-size: 22px; color: #FFFFFF;\">\ud83d\udca1 Did You Know?<\/strong>\n  <br \/><br \/>\n\n  The <strong style=\"color: #FFFFFF;\">sliding window<\/strong> technique is highly efficient because each element is visited at most <strong style=\"color: #FFFFFF;\">twice<\/strong>: once when the <strong style=\"color: #FFFFFF;\">right pointer<\/strong> expands the window and once when the <strong style=\"color: #FFFFFF;\">left pointer<\/strong> shrinks it. As a result, both <strong style=\"color: #FFFFFF;\">fixed-size<\/strong> and <strong style=\"color: #FFFFFF;\">variable-size<\/strong> sliding window algorithms run in <strong style=\"color: #FFFFFF;\">O(n)<\/strong> time, even though the window size changes dynamically during execution.\n\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Variable Window Example: Longest Substring With K Distinct Characters<\/strong><\/h2>\n\n\n\n<p>This is a classic medium-difficulty problem that shows the variable window pattern.<\/p>\n\n\n\n<p><strong>Problem:<\/strong> Given string s = &#8220;araaci&#8221; and k = 2, find the length of the longest substring with at most 2 distinct characters.<\/p>\n\n\n\n<ul>\n<li>You maintain a frequency map of characters in the current window, a left pointer, and a right pointer. Expand right at each step by adding the new character to the map.<\/li>\n\n\n\n<li>When the number of distinct characters in the map exceeds k, shrink from the left, remove the leftmost character, and move left forward. Keep doing this until the window is valid again.<\/li>\n\n\n\n<li>Track the maximum window length throughout. For &#8220;araaci&#8221; with k = 2, the answer is 4. The substring &#8220;araa&#8221; contains exactly 2 distinct characters: &#8216;a&#8217; and &#8216;r&#8217;.<\/li>\n<\/ul>\n\n\n\n<p><strong>The logic in code:<\/strong><\/p>\n\n\n\n<p>def longest_k_distinct(s, k): left = 0 char_map = {} max_len = 0 for right in range(len(s)): char_map[s[right]] = char_map.get(s[right], 0) + 1 while len(char_map) &gt; k: char_map[s[left]] -= 1 if char_map[s[left]] == 0: del char_map[s[left]] left += 1 max_len = max(max_len, right &#8211; left + 1) return max_len<\/p>\n\n\n\n<p><strong>Two pointers, one pass, O(n) time.<\/strong><\/p>\n\n\n\n<p><em>You explored sliding windows and how fixed\/variable windows optimize array and string problems like max sum and longest substring. Build interview-ready DSA skills with HCL GUVI\u2019s <\/em><a href=\"https:\/\/www.guvi.in\/courses\/bundles\/dsa-for-programmers\/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>DSA for Programmers.\u00a0<\/em><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Variable Window Example: Smallest Subarray With Sum \u2265 Target<\/strong><\/h2>\n\n\n\n<ul>\n<li><strong>Problem:<\/strong> Given arr = [2, 1, 5, 2, 3, 2] and target = 7, find the length of the smallest subarray with sum \u2265 7.<\/li>\n\n\n\n<li>Expand right until window_sum \u2265 target. Then shrink from the left as long as the sum stays \u2265 target; each valid shrink is a candidate for the minimum length. Record the smallest window length each time the condition holds.<\/li>\n\n\n\n<li><strong>For this <\/strong><a href=\"https:\/\/www.guvi.in\/blog\/array-data-structures-and-algorithms-in-java\/\"><strong>array<\/strong><\/a><strong>, the answer is 2. The subarray [5, 2] has a sum of 7 and a length of 2.<\/strong><\/li>\n\n\n\n<li>This is a tighter variant because you&#8217;re not just finding the longest valid window; you&#8217;re minimizing the length. The two-pointer approach handles both directions naturally.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Identify a Sliding Window Problem<\/strong><\/h2>\n\n\n\n<p>Recognizing the pattern is more than half the work. Here are the signals to look for.<\/p>\n\n\n\n<ul>\n<li>The problem involves a contiguous subarray or substring. The question asks for a maximum, minimum, longest, shortest, or count. The brute-force solution is obviously O(n\u00b2) with nested loops. The input involves an array, a string, or any linear sequence.<\/li>\n\n\n\n<li>If you see phrases like &#8220;subarray of size k,&#8221; &#8220;longest substring with at most,&#8221; or &#8220;minimum window that satisfies,&#8221; it&#8217;s almost certainly a sliding window problem.<\/li>\n\n\n\n<li>One quick test: can you represent the solution as a range [left, right] that moves through the array? If yes, the sliding window applies.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Common Sliding Window Problems to Practice<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Problem<\/strong><\/td><td><strong>Type<\/strong><\/td><td><strong>Key Pattern<\/strong><\/td><\/tr><tr><td>Max sum subarray of size k<\/td><td>Fixed<\/td><td>Add new, drop old<\/td><\/tr><tr><td>Longest substring with k distinct chars<\/td><td>Variable<\/td><td>Expand right, shrink left<\/td><\/tr><tr><td>Minimum window substring<\/td><td>Variable<\/td><td>Shrink until invalid; track min<\/td><\/tr><tr><td>Longest substring without repeating chars<\/td><td>Variable<\/td><td>Set or map tracks seen characters.<\/td><\/tr><tr><td>Find all anagrams in a string<\/td><td>Fixed<\/td><td>Character frequency comparison<\/td><\/tr><tr><td>Maximum consecutive ones after k flips<\/td><td>Variable<\/td><td>Count zeros and flip the constraint.<\/td><\/tr><tr><td>Subarray product less than k<\/td><td>Variable<\/td><td>Multiply in, divide out from the left.<\/td><\/tr><tr><td>Longest subarray with sum \u2264 k<\/td><td>Variable<\/td><td>Classic two-pointer shrink<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>All of these reduce to the same core pattern: a window defined by two pointers, moved intelligently based on the problem&#8217;s condition.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>When Not to Use Sliding Window<\/strong><\/h2>\n\n\n\n<ul>\n<li>The technique only works when the problem involves contiguous elements, meaning the subarray or substring must be a connected range in the original input. If the problem involves non-contiguous subsequences (like LIS or LCS), you need dynamic<a href=\"https:\/\/www.guvi.in\/blog\/how-to-learn-programming-language\/\" target=\"_blank\" rel=\"noreferrer noopener\"> programming<\/a> instead.<\/li>\n\n\n\n<li>Also, a sliding window assumes that adding or removing an element predictably affects the condition. Problems with complex constraints that don&#8217;t behave monotonically, where expanding the window doesn&#8217;t clearly worsen or improve the condition, may need a different approach.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>The sliding window technique is one of those tools that, once you understand it, makes a whole category of problems feel manageable. Fixed windows are the easier starting point to learn the add-and-drop mechanic first.&nbsp;<\/p>\n\n\n\n<p>Then move to variable windows with two pointers, which unlock a much wider set of problems. The key habit to build is recognizing when a brute-force nested loop is actually just a sliding window in disguise. Practice five to ten problems across both types, and the pattern becomes second nature.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>FAQs&nbsp;<\/strong><\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1783398830528\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>When should I use a fixed-size window vs a variable-size window?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Use fixed-size when k is given (e.g., subarray of size k); use variable-size when you need to meet a condition that dictates window length (e.g., \u2264 k distinct chars or sum \u2265 target).<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1783398836214\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>What\u2019s the core update step in a sliding-window algorithm?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Add the new element entering the window, remove the element leaving the window (or decrement its count), then update your answer (max\/min\/length\/count) in O(1).<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1783398844666\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>How do you keep a variable window valid?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Maintain a condition-driven loop: expand right to include elements, and while the condition is violated, shrink left until the window is valid again, updating the result each time it becomes valid.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1783398856540\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>Can sliding window handle negative numbers or non-monotonic conditions?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Fixed windows work fine with negatives; variable windows rely on monotonic behavior of the condition. If adding\/removing elements doesn&#8217;t predictably affect the condition, sliding window may not apply.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1783398864320\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>How do I spot sliding-window problems quickly?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Look for contiguous subarray\/substring requirements and asks for max\/min\/longest\/shortest\/count; if the brute-force solution uses nested loops over ranges, try reframing as a sliding window.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1783398888615\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>How do you handle tracking elements efficiently inside the window?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Use a hashmap or frequency array to count elements for strings or limited-range integers; update counts on include\/exclude and remove keys when count hits zero to keep checks O(1).<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1783398894868\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>What common mistakes should I avoid when coding sliding-window solutions?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Don&#8217;t place queries or updates inside inner loops, forget to handle edge cases (k > n, empty input), or fail to update left\/right correctly\u2014test with small arrays and boundary conditions.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>If you&#8217;ve ever solved an array or string problem using two nested loops and wondered whether there&#8217;s a smarter way, there is, and it&#8217;s called the &#8220;sliding window&#8221; technique. It&#8217;s one of the most practical and frequently tested patterns in coding interviews, and once you understand how it works, you&#8217;ll start spotting it in problems [&hellip;]<\/p>\n","protected":false},"author":63,"featured_media":121981,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[17],"tags":[],"views":"32","authorinfo":{"name":"Vishalini Devarajan","url":"https:\/\/www.guvi.in\/blog\/author\/vishalini\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/07\/sliding-window-technique-explained-300x117.webp","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/121511"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/63"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=121511"}],"version-history":[{"count":2,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/121511\/revisions"}],"predecessor-version":[{"id":121974,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/121511\/revisions\/121974"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/121981"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=121511"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=121511"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=121511"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}