{"id":"sliding-window-maximum","title":"Sliding Window Maximum","difficulty":"hard","patterns":["monotonic-stack","sliding-window"],"primaryConcept":"monotonic-stack-next-greater","concepts":["monotonic-stack-next-greater","array-sliding-window-fixed"],"problemForm":"core","companies":[],"category":"stacks-queues","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array-scalar","primaryParam":"nums","sizeMetric":"length","secondaryParams":{"k":{"strategy":"proportion","proportion":0.35}}},"description":"Given an integer array `nums` and an integer `k`, return an array of the maximum value in every contiguous window of length `k`.","examples":[{"input":"nums = [1,3,-1,-3,5,3,6,7], k = 3","output":"[3,3,5,5,6,7]","explanation":"The windows are [1,3,-1], [3,-1,-3], [-1,-3,5], [-3,5,3], [5,3,6], and [3,6,7]."},{"input":"nums = [1], k = 1","output":"[1]","explanation":"There is only one window."}],"constraints":[{"id":"1-k-nums-length-100000","text":"1 <= k <= len(nums) <= 100000"},{"id":"10000-nums-i-10000","text":"-10000 <= nums[i] <= 10000","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-10000,"max":10000}}],"starterCode":"class Solution:\n    def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:\n        # Your code here\n        pass","functionName":"maxSlidingWindow","testCases":[{"id":"1","input":{"nums":[1,3,-1,-3,5,3,6,7],"k":3},"expected":[3,3,5,5,6,7],"description":"Canonical mixed increasing and decreasing windows."},{"id":"2","input":{"nums":[1],"k":1},"expected":[1],"description":"Single element window."},{"id":"3","input":{"nums":[9,8,7,6],"k":2},"expected":[9,8,7],"description":"Strictly decreasing input keeps older indices until they expire."},{"id":"4","input":{"nums":[1,2,3,4],"k":2},"expected":[2,3,4],"description":"Strictly increasing input repeatedly pops smaller trailing values."},{"id":"5","input":{"nums":[4,4,4],"k":2},"expected":[4,4],"description":"Equal values should remain valid until they leave the window."},{"id":"h1","input":{"nums":[2,1],"k":2},"expected":[2],"description":"A full-length window returns one maximum."},{"id":"h2","input":{"nums":[-1,-3,-5],"k":2},"expected":[-1,-3],"description":"Negative values still follow the same window maximum rule."},{"id":"h3","input":{"nums":[7,2,4],"k":2},"expected":[7,4],"description":"The leading maximum drops out after one shift."},{"id":"h4","input":{"nums":[4,2,12,3,8],"k":3},"expected":[12,12,12],"description":"A stable maximum persists across several windows."},{"id":"h5","input":{"nums":[9,8,8,7,6],"k":4},"expected":[9,8],"description":"Equal values at the window boundary are handled correctly."},{"id":"public-11","input":{"nums":[1,-1],"k":1},"expected":[1,-1],"description":"Window size one returns each element unchanged."},{"id":"public-12","input":{"nums":[2,2,1,2],"k":3},"expected":[2,2],"description":"Duplicate maxima remain valid across overlapping windows."},{"id":"public-13","input":{"nums":[-7,-8,7,5,7,1,6,0],"k":4},"expected":[7,7,7,7,7],"description":"A repeated positive maximum dominates mixed negative and positive windows."},{"id":"public-14","input":{"nums":[10,9,8],"k":3},"expected":[10],"description":"A full-length decreasing window returns the first element as the only maximum."}],"hints":[{"level":1,"content":"Keep indices, not values, so you can tell when an entry leaves the current window.","revealPattern":false},{"level":2,"content":"Maintain the candidate queue so values decrease from front to back.","revealPattern":true},{"level":3,"content":"The front of the candidate queue is the maximum for the current full window.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"How should each window get its maximum?","decisionPrompt":"The window [3, -1, -3] shifts right as 5 arrives. Choose how the maximum of the new window is produced.","approaches":[{"id":"rescan-windows","name":"Scan each window for its maximum","summary":"For every start position, look at all k values and take the largest.","decisionReason":"Every window rescans k values from scratch, so a large k makes the whole pass cost about n times k even though consecutive windows differ by one value.","complexity":{"time":"O(n*k)","space":"O(1)"},"tradeoffs":["Rescans k values per window, so the work grows with both n and k."],"isOptimal":false},{"id":"monotonic-deque","name":"Carry candidates forward from the previous window","summary":"Hold on to the values already in the window and keep only the ones that could still be reported as a maximum.","decisionReason":"The window that starts at index 2 shares -1 and -3 with the one before it, so carrying those values across the shift replaces the rescan with a small number of removals per index.","complexity":{"time":"O(n)","space":"O(k)"},"tradeoffs":["Needs a structure that can remove from both ends, plus room for up to k carried indices."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-state","title":"Initialize the candidate queue","description":"Create an empty front-and-back queue for candidate indices.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"initializes_empty_stack","scope":"init-stack","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Prepare the candidate structure before scanning nums.","doneWhen":"An empty front-and-back candidate structure exists before the main scan.","shouldFailWhen":"This step should fail if there is no mutable candidate structure.","roles":["candidate index queue"],"mustProve":["empty candidate queue"],"mustNotAccept":["only scalar state"],"proofSnippets":[{"id":"py-init-candidate-deque","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []"}]},"hint":"Use a structure that can remove from the front and back while storing candidate indices."},{"id":"scan-indexed","title":"Scan nums with indices","description":"Iterate through nums from left to right while keeping each index available.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence_with_index","scope":"loop-with-index","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Traverse nums in order with both the current index and value available.","doneWhen":"The main loop visits nums left to right and exposes the current index.","shouldFailWhen":"This step should fail if the code does not scan nums or loses the current index.","roles":["input sequence","current index","current value"],"mustProve":["indexed scan over nums"],"mustNotAccept":["looping over a different sequence","value-only traversal that cannot expire indices"],"proofSnippets":[{"id":"py-enumerate-nums","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    for i, num in enumerate(nums):\n        pass"}]},"hint":"The index tells you whether a candidate entry is outside the current window."},{"id":"evict-stale","title":"Remove expired front indices","description":"Before reading candidates, remove a front index once it no longer belongs to the current k-sized window.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"evicts_bounded_front_entry","scope":"evict-stale","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Keep the front candidate inside the current window boundary.","doneWhen":"The code checks the candidate front against the current index and k, then removes it from the front when stale.","shouldFailWhen":"This step should fail if old front indices are never removed or removal is not tied to the window bound.","roles":["candidate front","current index","window size"],"mustProve":["front index compared with a current-index window bound","front removal on stale entries"],"mustNotAccept":["tail pop only","unbounded front removal"],"proofSnippets":[{"id":"py-evict-stale-front","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)"}]},"hint":"The candidate front can only answer the current window if its index is still inside that window."},{"id":"pop-tail","title":"Discard smaller trailing indices","description":"Pop from the back while the current value dominates the trailing candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pops_tail_entries_after_top_comparison","scope":"pop-tail","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Maintain decreasing value order inside the candidate queue.","doneWhen":"The comparison loop removes dominated trailing candidates from the back.","shouldFailWhen":"This step should fail if the code checks the condition but does not pop dominated entries.","roles":["candidate back","current value","tail pop"],"mustProve":["tail pop under stack-top comparison"],"mustNotAccept":["a comparison with no removal","front eviction in place of tail cleanup"],"proofSnippets":[{"id":"py-pop-smaller-tail","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)\n        while q and nums[q[-1]] < num:\n            q.pop()"}]},"hint":"A smaller value behind the current value cannot win any future window that includes both."},{"id":"push-index","title":"Push the current index","description":"After stale and dominated indices are gone, append the current index as a candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_current_index","scope":"push-current","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Store indices so later iterations can check both value order and window membership.","doneWhen":"The current scan index is pushed onto the candidate queue after cleanup.","shouldFailWhen":"This step should fail if the code pushes values instead of indices or pushes before cleanup.","roles":["current index","candidate queue"],"mustProve":["current index push"],"mustNotAccept":["pushing current values","no candidate push"],"proofSnippets":[{"id":"py-push-current-index","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)\n        while q and nums[q[-1]] < num:\n            q.pop()\n        q.append(i)"}]},"hint":"Store the index so stale candidates can be removed by position."},{"id":"append-max","title":"Append the front value for each full window","description":"Once the first full window is reached, append the value at the candidate front index to the result.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"appends_front_indexed_value_to_result","scope":"append-window-max","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Emit exactly one maximum for each full window.","doneWhen":"The code waits until the current index reaches k - 1, then appends the value selected by the candidate front to the result.","shouldFailWhen":"This step should fail if it appends the current value, appends before the first full window, or does not read through the candidate front.","roles":["window-ready guard","candidate front","result sequence"],"mustProve":["bounded result append","source value selected through candidate front"],"mustNotAccept":["unbounded append","append current value directly"],"proofSnippets":[{"id":"py-append-front-value","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    res = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)\n        while q and nums[q[-1]] < num:\n            q.pop()\n        q.append(i)\n        if i >= k - 1:\n            res.append(nums[q[0]])"}]},"hint":"The candidate front points to the maximum of the current full window."},{"id":"return-result","title":"Return the result array","description":"Return the accumulated maxima after the scan finishes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the sequence built by appending each window maximum.","doneWhen":"The function returns the same result sequence that received window maximum appends.","shouldFailWhen":"This step should fail if the function returns the candidate queue, a scalar, or another unrelated value.","roles":["result sequence","terminal return"],"mustProve":["returned result sequence"],"mustNotAccept":["returning the candidate queue","returning only the final maximum"],"proofSnippets":[{"id":"py-return-window-results","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    res = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)\n        while q and nums[q[-1]] < num:\n            q.pop()\n        q.append(i)\n        if i >= k - 1:\n            res.append(nums[q[0]])\n    return res"}]},"hint":"Return the accumulated maxima array."}],"slides":[{"id":"read-the-problem","chapter":"Understand","kind":"info","eyebrow":"Read the problem","title":"The largest value in every sliding window","workspacePanel":"problem","body":["You get an array nums and a window length k. The window starts at the left, covers k values, and slides one step right at a time. For each position you report the largest value the window currently covers.","The result holds one value for every window position, in the order the windows appear, so an array of length n with window length k produces n - k + 1 answers."]},{"id":"brute-force","chapter":"The obvious way","kind":"code-trace","eyebrow":"Try it directly","title":"Rescan every window for its maximum","summary":"The trace below reports the right maximum every time. As the window slides, count how many of its values the inner loop has already compared once.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\nfor start in range(len(nums) - k + 1):\n    best = nums[start]\n    for j in range(start + 1, start + k):\n        if nums[j] > best:\n            best = nums[j]\n    result.append(best)","steps":[{"id":"first-window","title":"The first window scans all three values","codeLine":4,"summary":"The window [1, 3, -1] is checked value by value. The largest, 3, is the first answer.","state":{"nums":[1,3,-1,-3,5,3,6,7],"left":0,"right":2,"labels":{"nums":"nums"}}},{"id":"slide-one","title":"Sliding one step rescans the overlap","codeLine":3,"summary":"The window moves to [3, -1, -3]. Values 3 and -1 sat in the previous window too, yet they are compared again from scratch.","state":{"nums":[1,3,-1,-3,5,3,6,7],"left":1,"right":3,"labels":{"nums":"nums"}}},{"id":"slide-two","title":"The next window rescans the same overlap again","codeLine":4,"summary":"The window reaches [-1, -3, 5]. Two of its three values were already scanned a moment ago, and the inner loop walks them once more.","state":{"nums":[1,3,-1,-3,5,3,6,7],"left":2,"right":4,"labels":{"nums":"nums"}}},{"id":"overlap-repeats","title":"Every window redoes the overlap","codeLine":4,"summary":"Each window shares k-1 values with the last, so almost every comparison is repeated. The larger k is, the more each value is re-examined.","state":{"nums":[1,3,-1,-3,5,3,6,7],"left":3,"right":5,"labels":{"nums":"nums"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nfor (let start = 0; start < ((nums.length - k) + 1); start++) {\n    let best = nums[start];\n    for (let j = (start + 1); j < (start + k); j++) {\n        if (nums[j] > best) {\n            best = nums[j];\n        }\n    }\n    result.push(best);\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<number> = [];\nfor (let start = 0; start < ((nums.length - k) + 1); start++) {\n    let best = nums[start];\n    for (let j = (start + 1); j < (start + k); j++) {\n        if (nums[j] > best) {\n            best = nums[j];\n        }\n    }\n    result.push(best);\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> result = new ArrayList<>();\nfor (int start = 0; start < ((nums.size() - k) + 1); start++) {\n    int best = nums.get(start);\n    for (int j = (start + 1); j < (start + k); j++) {\n        if (nums.get(j) > best) {\n            best = nums.get(j);\n        }\n    }\n    result.add(best);\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> result = new();\nfor (int start = 0; start < nums.Count - k + 1; start++) {\n    int best = nums[start];\n    for (int j = start + 1; j < start + k; j++) {\n        if (nums[j] > best) {\n            best = nums[j];\n        }\n    }\n    result.Add(best);\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> result;\nfor (int start = 0; start < ((nums.size() - k) + 1); start++) {\n    int best = nums[start];\n    for (int j = (start + 1); j < (start + k); j++) {\n        if (nums[j] > best) {\n            best = nums[j];\n        }\n    }\n    result.push_back(best);\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8},"7":{"startLine":9,"endLine":10}}}}},"body":["For each window, an inner loop walks all k values to find the largest."]},{"id":"count-the-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Count the cost","title":"Across all the windows, how much value-checking does this add up to?","workspacePanel":"trace","summary":"The trace above walks one window. The array has length n and each window holds k values.","options":[{"id":"n-times-k","label":"About n times k, since each of the n - k + 1 windows rescans all k values","rationale":"Every window starts its scan over, so each of the n - k + 1 windows does k comparisons: (n - k + 1) times k reads in total. When k is large that product, about n times k, dominates the run.","isCorrect":true},{"id":"linear","label":"About n, one check per value","rationale":"A single pass would be n, but nothing is shared between windows here. Each of the n - k + 1 windows rescans its k values, so the work multiplies rather than divides.","isCorrect":false},{"id":"n-log-n","label":"About n log n, like sorting once","rationale":"No sorting happens, and the work is not logarithmic. Each window does linear work in k, so the total is n times k, not n log n.","isCorrect":false}],"answer":"About n times k. Each of the n - k + 1 windows rescans all k of its values, and the windows overlap heavily, so the same values are checked again and again."},{"id":"trick-bridge","chapter":"The trick","kind":"info","eyebrow":"Cut the repeated work","title":"The next window reuses almost all of the last one","workspacePanel":"visualizer","body":["The n times k cost came from rebuilding the maximum even though the next window keeps k-1 of the same values.","The panel holds the window [3, -1, -3], with 5 about to arrive at the right edge and 3 about to fall off the left."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"trick-bridge-state","state":{"nums":[1,3,-1,-3,5,3,6,7],"labels":{"nums":"nums"},"left":1,"right":3,"arrays":[{"name":"values still in the window","values":[3,-1,-3]}]}}]}},{"id":"approach-selection","chapter":"The trick","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"How should each window get its maximum?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"nums":[1,3,-1,-3,5,3,6,7],"labels":{"nums":"nums"},"left":1,"right":3,"arrays":[{"name":"carried candidates","values":[3,-1,-3]}]}}]}},{"id":"what-to-keep","chapter":"The trick","kind":"case-probe","eyebrow":"Rule out candidates","title":"With the window at [-1, -3, 5], which carried values can be thrown away?","workspacePanel":"visualizer","summary":"The panel holds 3, -1, and -3 in arrival order. 5 then arrives at index 4, and with k = 3 the window becomes [-1, -3, 5], so 3 is already behind its left edge.","options":[{"id":"only-not-dominated","label":"-1 and -3, because 5 arrived later and is larger than both","rationale":"Any window from here on that still covers -1 or -3 also covers index 4, and 5 beats both of them there. Neither can be reported again, whatever arrives next.","isCorrect":true},{"id":"every-value","label":"-3 only, because -1 is the larger of the two carried values","rationale":"Ranking -1 against -3 answers the wrong comparison. Every window still to come that covers -1 also covers the larger 5, so -1 is finished as well.","isCorrect":false},{"id":"only-largest","label":"Neither of them, because both are still inside the window","rationale":"Sitting inside the window keeps a value present without making it reportable. With 5 at index 4 behind them, no window that covers -1 or -3 can name either one as its maximum.","isCorrect":false}],"answer":"-1 and -3 can both go, leaving 5 as the only candidate this window needs. 5 sits at a later index and is larger, so every remaining window that covers -1 or -3 covers 5 too. A carried value can be dropped as soon as a larger value arrives behind it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"what-to-keep-state","state":{"nums":[1,3,-1,-3,5,3,6,7],"labels":{"nums":"nums"},"left":1,"right":3,"arrays":[{"name":"surviving candidates (oldest to newest)","values":[3,-1,-3]}]}}]}},{"id":"name-the-structure","chapter":"The trick","kind":"case-probe","eyebrow":"Keep expiration visible","title":"Two candidates both hold 5. What should be stored for each one?","workspacePanel":"visualizer","summary":"This array holds 5 at index 4 and again at index 6, and the window's left edge has moved to index 5.","options":[{"id":"pop-back-push-back","label":"The position where each candidate entered","rationale":"One of these 5s came from index 4 and the other from index 6. A window starting at index 5 has passed the first and still covers the second, and only the positions say which is which.","isCorrect":true},{"id":"pop-front","label":"The value each candidate carries","rationale":"Two stored 5s compare as equal, so nothing distinguishes the copy the window has already passed from the copy still inside it.","isCorrect":false},{"id":"sorted-insert","label":"How many copies of each value are held","rationale":"A count of two says both copies exist without saying where either one sits, so it cannot say when either copy falls behind the left edge.","isCorrect":false}],"answer":"The position. Index 4 falls behind a window that starts at index 5 while index 6 is still inside it, even though both values equal 5, so the candidates are stored as indices. Old indices leave from the front, values a later arrival has beaten leave from the back, and new indices join at the back, which is exactly a deque.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"name-the-structure-state","state":{"nums":[1,3,-1,-3,5,3,5,7],"labels":{"nums":"nums"},"left":5,"right":6,"arrays":[{"name":"equal candidate values","values":[5,5]}]}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"A deque of decreasing candidates","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[1,3,-1,-3,5,3,6,7],"labels":{"nums":"nums"},"left":0,"right":2,"arrays":[{"name":"deque values (front to back)","values":[3,-1]}]}}]},"body":["Because a candidate leaves the moment a larger value arrives behind it, the values still in the deque decrease from front to back, and the front is the largest value the window covers.","Each step: drop the front if its index has fallen behind the window, pop every smaller value off the back, then add the new index at the back. From the first full window onward, the value at the front index is recorded."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the deque","title":"Trace the candidate deque","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-window","state":{"nums":[1,3,-1,-3,5,3,6,7],"labels":{"nums":"nums"},"left":0,"right":2,"arrays":[{"name":"deque values (front to back)","values":[3,-1]}]}},{"id":"front-expires","state":{"nums":[1,3,-1,-3,5,3,6,7],"labels":{"nums":"nums"},"left":2,"right":4,"arrays":[{"name":"deque values (front to back)","values":[5]}]}},{"id":"sweep-back","state":{"nums":[1,3,-1,-3,5,3,6,7],"labels":{"nums":"nums"},"left":4,"right":6,"arrays":[{"name":"deque values (front to back)","values":[6]}]}}]},"beats":[{"id":"first-window","title":"The window records 3 from the front. Why is -1 still on the deque?","summary":"The first window [1, 3, -1] is complete. Value 1 was popped when 3 arrived, and the deque now holds 3 then -1.","prompt":"3 is the front, so this window reports 3.","options":[{"id":"three","label":"3 falls out of the window before -1 does, and nothing larger has arrived behind -1","rationale":"Index 1 drops behind the left edge two steps from here while index 2 is still covered, so -1 is the carried candidate for windows that 3 is no longer part of.","isCorrect":true},{"id":"minus-one","label":"Every index that has been scanned stays on the deque until it leaves the window","rationale":"Value 1 was scanned and is already gone, popped off the back when the larger 3 arrived at a later index.","isCorrect":false},{"id":"one","label":"The deque always keeps a second candidate so the front has something behind it","rationale":"Nothing reserves a spot behind the front. A single value can be the whole deque, which happens as soon as one arrival beats everything carried.","isCorrect":false}],"answer":"3 is reported now. -1 stays because nothing larger has arrived behind it: for any later window that no longer holds 3, the best candidate seen so far is -1, and the deque keeps it for exactly that future."},{"id":"front-expires","title":"If -2 had arrived at index 4 instead of 5, would 3 still be on the deque?","summary":"5 arrived at index 4 and cleared the deque down to itself, so this window reports 5. The deque it cleared was 3 at index 1, then -1, then -3.","prompt":"Rerun that step with nums[4] = -2 in place of 5.","options":[{"id":"expire-front","label":"No. Index 1 sits outside a window that starts at index 2, whatever value arrives","rationale":"The window covering index 4 runs from index 2 to index 4, so index 1 is out by position alone. It is dropped from the front before the arriving value is compared with anything.","isCorrect":true},{"id":"keep-front","label":"Yes. -2 is smaller than 3, so nothing removes 3 and it stays at the front","rationale":"Comparing values only decides what leaves from the back. Left in place, index 1 would report 3 for a window that no longer contains it.","isCorrect":false},{"id":"pop-back-only","label":"No. The shift clears -1 and -3 as well, since carried values do not outlive a move","rationale":"Moving the window only removes indices that fall behind its left edge. -3 leaves because -2 beats it from behind, while -1 is larger than -2 and stays.","isCorrect":false}],"answer":"No. The window covering index 4 starts at index 2, so index 1 leaves either way. With 5 arriving the two rules overlap, because 5 also beats 3 from behind. With -2 arriving, the position check is the only thing that removes 3, and the deque ends as -1 then -2, reporting -1 for the window [-1, -3, -2]."},{"id":"sweep-back","title":"One arrival just popped two candidates. What does that do to the total work?","summary":"The deque held 5 at index 4 then 3 at index 5. 6 arrived at index 6, popped both off the back, and now stands alone, so this window reports 6.","prompt":"Add up the pops over a whole scan of nums.","options":[{"id":"two","label":"Every index is pushed once and popped at most once, so the pops total at most n","rationale":"5 and 3 could be popped here only because two earlier steps pushed them, and neither can be popped a second time. The pops across the scan can never outnumber the pushes.","isCorrect":true},{"id":"one","label":"One step can pop up to k candidates, so the pops can reach about n times k","rationale":"A step that pops k candidates needs k earlier steps that each pushed one and popped nothing. The long sweeps are paid for by the cheap steps around them.","isCorrect":false},{"id":"zero","label":"The popping repeats the rescan, so the deque saves memory rather than comparisons","rationale":"The deque holds up to k indices, which is more memory than the rescan needed. What it takes away is the repeated comparison of values that are still inside the window.","isCorrect":false}],"answer":"The pops total at most n. Each index joins the deque once and leaves at most once, so a sweep that clears 5 and 3 in one step is work that later steps no longer have to do, and the whole scan stays proportional to n rather than to n times k."}]},{"id":"skip-back-pop-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can the deque just append every new index?","workspacePanel":"trace","summary":"The version below drops the front by the window bound and then appends every index it scans, on nums = [1, 3, 1] with k = 2.","pitfall":"The code below appends every index and only expires the front, never popping smaller values off the back.","whyItMatters":"Without popping the back, a smaller older value stays in front of a larger newer one, so the front is no longer the maximum. Pop while the back value is smaller than the arriving one, nums[deque[-1]] < nums[i], so the deque stays decreasing and the front always holds the largest.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"q = deque()\nres = []\nfor i in range(len(nums)):\n    if q and q[0] <= i - k:\n        q.popleft()\n    q.append(i)\n    if i >= k - 1:\n        res.append(nums[q[0]])","steps":[{"id":"push-one","title":"Index 0 (value 1) goes on the deque","codeLine":5,"summary":"nums = [1, 3, 1], k = 2. Index 0 holds value 1 and is appended. The deque front is index 0.","state":{"i":0,"rows":[{"label":"nums","values":[1,3,1]}],"stack":[1],"stackActive":0,"labels":{"stack":"deque (values)"}}},{"id":"push-three-behind","title":"Index 1 (value 3) is appended behind the 1","codeLine":5,"summary":"Value 3 arrives. With no back-popping it is simply appended, so the deque now holds value 1 then value 3, no longer decreasing.","state":{"i":1,"rows":[{"label":"nums","values":[1,3,1]}],"stack":[1,3],"stackActive":1,"labels":{"stack":"deque (values)"}}},{"id":"front-wrong","title":"The front reports 1, but the window maximum is 3","codeLine":7,"summary":"The first window [1, 3] is complete. The front is value 1, so res records 1, but the largest value in [1, 3] is 3.","state":{"i":1,"rows":[{"label":"nums","values":[1,3,1]},{"label":"res","values":[1],"changed":[0]}],"stack":[1,3],"stackActive":0,"labels":{"stack":"deque (values)"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const q = new Deque([]);\nconst res = [];\nfor (let i = 0; i < nums.length; i++) {\n    if (q.size() > 0 && q.front() <= (i - k)) {\n        q.popFront();\n    }\n    q.pushBack(i);\n    if (i >= (k - 1)) {\n        res.push(nums[q.front()]);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":11}},"alternateStyles":{"close-to-source":{"code":"const q = new Deque([]);\nconst res = [];\nfor (let i = 0; i < nums.length; i++) {\n    if (q.size() > 0 && q.front() <= (i - k)) {\n        if (q.size() === 0) throw new Error(\"IndexError\");\n        const poppedValue = q.popFront();\n    }\n    q.pushBack(i);\n    if (i >= (k - 1)) {\n        res.push(nums[q.front()]);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9,"8":10},"statementBundles":{"5":{"startLine":5,"endLine":7},"8":{"startLine":10,"endLine":12}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const q: Deque<number> = new Deque([]);\nconst res: Array<number> = [];\nfor (let i = 0; i < nums.length; i++) {\n    if (q.size() > 0 && q.front()! <= (i - k)) {\n        q.popFront();\n    }\n    q.pushBack(i);\n    if (i >= (k - 1)) {\n        res.push(nums[q.front()!]);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":11}},"alternateStyles":{"close-to-source":{"code":"const q: Deque<number> = new Deque([]);\nconst res: Array<number> = [];\nfor (let i = 0; i < nums.length; i++) {\n    if (q.size() > 0 && q.front()! <= (i - k)) {\n        if (q.size() === 0) throw new Error(\"IndexError\");\n        const poppedValue = q.popFront();\n    }\n    q.pushBack(i);\n    if (i >= (k - 1)) {\n        res.push(nums[q.front()!]);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9,"8":10},"statementBundles":{"5":{"startLine":5,"endLine":7},"8":{"startLine":10,"endLine":12}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"Deque<Integer> q = new ArrayDeque<>();\nList<Integer> res = new ArrayList<>();\nfor (int i = 0; i < nums.size(); i++) {\n    if ((!q.isEmpty() && q.peekFirst() <= (i - k))) {\n        q.pollFirst();\n    }\n    q.addLast(i);\n    if (i >= (k - 1)) {\n        res.add(nums.get(q.peekFirst()));\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"Queue<int> q = new();\nList<int> res = new();\nfor (int i = 0; i < nums.Count; i++) {\n    if (q.Count > 0 && q.Peek() <= i - k) {\n        q.Dequeue();\n    }\n    q.Enqueue(i);\n    if (i >= k - 1) {\n        res.Add(nums[q.Peek()]);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"deque<int> q;\nvector<int> res;\nfor (int i = 0; i < nums.size(); i++) {\n    if ((!q.empty() && q[0] <= (i - k))) {\n        q.pop_front();\n    }\n    q.push_back(i);\n    if (i >= (k - 1)) {\n        res.push_back(nums[q[0]]);\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":11}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which window sizes could break this?","workspacePanel":"visualizer","body":["The constraints allow any k from 1 up to the length of nums, and both ends of that range are legal inputs the same two removals have to handle.","Two to try before coding: k = 1, where every window covers a single value, and k = n, where one window covers the whole array and never slides."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[1,3,-1,-3,5,3,6,7],"labels":{"nums":"nums"},"left":0,"right":2,"arrays":[{"name":"deque values (front to back)","values":[]}]}}]}},{"id":"k-one-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"With k = 1, what does the front hold at each step?","workspacePanel":"visualizer","summary":"nums = [4, -2, 7], k = 1: every window covers exactly one value.","options":[{"id":"value-itself","label":"The value at the index just scanned","rationale":"A new value pops everything smaller off the back before it is placed, and with k = 1 the previous index has already expired, so the front is always the current value.","isCorrect":true},{"id":"running-max","label":"The largest value seen so far","rationale":"A running maximum would never let an earlier large value leave, but with k = 1 only the current value is in the window, so the front must be that value.","isCorrect":false},{"id":"empty","label":"Nothing, because a window of one value is too small to report","rationale":"A window of size 1 is a complete window, so every value is recorded. The first full window is reached at index 0.","isCorrect":false}],"answer":"The value at the index just scanned. The previous index has already slid out, and the new value clears any smaller back candidate, so the front is the current value and the answer is nums itself: [4, -2, 7].","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"k-one-state","state":{"nums":[4,-2,7],"left":1,"right":1,"labels":{"nums":"nums"},"arrays":[{"name":"deque values (front to back)","values":[-2]}]}}]}},{"id":"k-equals-n-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"With k = n, what keeps the front correct when nothing ever expires?","workspacePanel":"visualizer","summary":"nums = [2, 5, 1, 3], k = 4: one window spans all four values, so no index ever leaves it.","options":[{"id":"back-pop-only","label":"Popping the back as larger values arrive","rationale":"No index expires, so the front-dropping never fires. Each larger value pops the smaller ones off the back, and after the scan the front is 5, the maximum of the only window.","isCorrect":true},{"id":"front-expire","label":"Dropping the front as the window slides","rationale":"The window never slides past any index when k = n, so nothing ever expires. The back-popping is what keeps the front right.","isCorrect":false},{"id":"needs-rescan","label":"A final rescan of all four values at the end","rationale":"No rescan is needed. The back-popping has already left the global maximum alone at the front by the time the window is complete.","isCorrect":false}],"answer":"The back-popping. Nothing expires when one window covers everything, so the front never drops by the window bound. 5 pops 2 off the back, then 3 pops the smaller 1, so the deque settles to 5 then 3 with 5 at the front, the maximum of the single window [2, 5, 1, 3].","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"k-equals-n-state","state":{"nums":[2,5,1,3],"left":0,"right":3,"labels":{"nums":"nums"},"arrays":[{"name":"deque values (front to back)","values":[5,3]}]}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Build the candidate deque","summary":"Every index gets the same three deque moves before its window is reported.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"nums":[1,3,-1,-3,5,3,6,7],"labels":{"nums":"nums"},"left":0,"right":2,"arrays":[{"name":"deque values (front to back)","values":[]}]}}]},"body":["Walk nums once with a deque of candidate indices. At each index, drop the front if it has fallen behind the window, pop every smaller value off the back, then add the current index.","From index k - 1 onward every position completes a window, so read nums at the front index and append it to the result before moving on. Return that result when the scan ends."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the candidate deque","eyebrow":"Code the rule","summary":"Follow the deque moves in order.","workspacePanel":"code","checkpoints":[{"id":"init-state","title":"Initialize the candidate queue","description":"Create an empty front-and-back queue for candidate indices.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"initializes_empty_stack","scope":"init-stack","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Prepare the candidate structure before scanning nums.","doneWhen":"An empty front-and-back candidate structure exists before the main scan.","shouldFailWhen":"This step should fail if there is no mutable candidate structure.","roles":["candidate index queue"],"mustProve":["empty candidate queue"],"mustNotAccept":["only scalar state"],"proofSnippets":[{"id":"py-init-candidate-deque","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []"}]},"hint":"Use a structure that can remove from the front and back while storing candidate indices."},{"id":"scan-indexed","title":"Scan nums with indices","description":"Iterate through nums from left to right while keeping each index available.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence_with_index","scope":"loop-with-index","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Traverse nums in order with both the current index and value available.","doneWhen":"The main loop visits nums left to right and exposes the current index.","shouldFailWhen":"This step should fail if the code does not scan nums or loses the current index.","roles":["input sequence","current index","current value"],"mustProve":["indexed scan over nums"],"mustNotAccept":["looping over a different sequence","value-only traversal that cannot expire indices"],"proofSnippets":[{"id":"py-enumerate-nums","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    for i, num in enumerate(nums):\n        pass"}]},"hint":"The index tells you whether a candidate entry is outside the current window."},{"id":"evict-stale","title":"Remove expired front indices","description":"Before reading candidates, remove a front index once it no longer belongs to the current k-sized window.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"evicts_bounded_front_entry","scope":"evict-stale","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Keep the front candidate inside the current window boundary.","doneWhen":"The code checks the candidate front against the current index and k, then removes it from the front when stale.","shouldFailWhen":"This step should fail if old front indices are never removed or removal is not tied to the window bound.","roles":["candidate front","current index","window size"],"mustProve":["front index compared with a current-index window bound","front removal on stale entries"],"mustNotAccept":["tail pop only","unbounded front removal"],"proofSnippets":[{"id":"py-evict-stale-front","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)"}]},"hint":"The candidate front can only answer the current window if its index is still inside that window."},{"id":"pop-tail","title":"Discard smaller trailing indices","description":"Pop from the back while the current value dominates the trailing candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pops_tail_entries_after_top_comparison","scope":"pop-tail","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Maintain decreasing value order inside the candidate queue.","doneWhen":"The comparison loop removes dominated trailing candidates from the back.","shouldFailWhen":"This step should fail if the code checks the condition but does not pop dominated entries.","roles":["candidate back","current value","tail pop"],"mustProve":["tail pop under stack-top comparison"],"mustNotAccept":["a comparison with no removal","front eviction in place of tail cleanup"],"proofSnippets":[{"id":"py-pop-smaller-tail","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)\n        while q and nums[q[-1]] < num:\n            q.pop()"}]},"hint":"A smaller value behind the current value cannot win any future window that includes both."},{"id":"push-index","title":"Push the current index","description":"After stale and dominated indices are gone, append the current index as a candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_current_index","scope":"push-current","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Store indices so later iterations can check both value order and window membership.","doneWhen":"The current scan index is pushed onto the candidate queue after cleanup.","shouldFailWhen":"This step should fail if the code pushes values instead of indices or pushes before cleanup.","roles":["current index","candidate queue"],"mustProve":["current index push"],"mustNotAccept":["pushing current values","no candidate push"],"proofSnippets":[{"id":"py-push-current-index","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)\n        while q and nums[q[-1]] < num:\n            q.pop()\n        q.append(i)"}]},"hint":"Store the index so stale candidates can be removed by position."},{"id":"append-max","title":"Append the front value for each full window","description":"Once the first full window is reached, append the value at the candidate front index to the result.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"appends_front_indexed_value_to_result","scope":"append-window-max","readMode":"stack-value-query-v1"}]},"semanticSpec":{"intent":"Emit exactly one maximum for each full window.","doneWhen":"The code waits until the current index reaches k - 1, then appends the value selected by the candidate front to the result.","shouldFailWhen":"This step should fail if it appends the current value, appends before the first full window, or does not read through the candidate front.","roles":["window-ready guard","candidate front","result sequence"],"mustProve":["bounded result append","source value selected through candidate front"],"mustNotAccept":["unbounded append","append current value directly"],"proofSnippets":[{"id":"py-append-front-value","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    res = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)\n        while q and nums[q[-1]] < num:\n            q.pop()\n        q.append(i)\n        if i >= k - 1:\n            res.append(nums[q[0]])"}]},"hint":"The candidate front points to the maximum of the current full window."},{"id":"return-result","title":"Return the result array","description":"Return the accumulated maxima after the scan finishes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"semanticSpec":{"intent":"Return the sequence built by appending each window maximum.","doneWhen":"The function returns the same result sequence that received window maximum appends.","shouldFailWhen":"This step should fail if the function returns the candidate queue, a scalar, or another unrelated value.","roles":["result sequence","terminal return"],"mustProve":["returned result sequence"],"mustNotAccept":["returning the candidate queue","returning only the final maximum"],"proofSnippets":[{"id":"py-return-window-results","language":"python","code":"def maxSlidingWindow(nums, k):\n    q = []\n    res = []\n    for i, num in enumerate(nums):\n        if q and q[0] <= i - k:\n            q.pop(0)\n        while q and nums[q[-1]] < num:\n            q.pop()\n        q.append(i)\n        if i >= k - 1:\n            res.append(nums[q[0]])\n    return res"}]},"hint":"Return the accumulated maxima array."}]},{"id":"complete","chapter":"Code","kind":"complete","title":"What to carry forward","eyebrow":"Take it with you","summary":"The deque carries candidate indices from one window into the next, so no window is ever rescanned.","workspacePanel":"code","body":["The rescan paid about n times k because every window built its maximum from nothing.","Carrying candidate indices across each shift replaces that with a few removals per index, which brings the pass to O(n) time and O(k) space."],"takeaways":[{"title":"The front is the window maximum","body":"Candidates decrease from front to back, so the front index always points at the largest value currently in the window."},{"title":"Pop the back, drop the stale front","body":"A value with a larger value behind it can never be reported again, so it leaves from the back, while an index that falls behind the window leaves from the front."},{"title":"Linear because each index moves twice","body":"Every index is added once and removed once, so the total work is O(n) even though a single step can pop several candidates."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
