{"id":8083,"date":"2025-07-20T17:58:02","date_gmt":"2025-07-20T12:28:02","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=8083"},"modified":"2025-07-21T12:26:42","modified_gmt":"2025-07-21T06:56:42","slug":"sliding-window-maximum","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/sliding-window-maximum\/","title":{"rendered":"Sliding Window Maximum"},"content":{"rendered":"\n<!-- Longest -->\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style> \n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #f8c291;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2{\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n.wp_blog_explanation h5{\n  color: var(--primary);\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n.wp_blog_explanation code {\n  background: #f9cea6;\n  color: #2d2d2d;\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n}\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0,0,0,0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\"> \n    <h1 class=\"wp_blog_main-heading\"><\/h1>\n    <div class=\"wp_blog_explanation\">\n        <h2>Problem Statement:<\/h2>\n\n        <p>\n           You are given an array of integers <code>nums<\/code>, there is a sliding window of size <code>k<\/code> which is moving from the very left of the array to the very right. You can only see the <code>k<\/code> numbers in the window. Each time the sliding window moves right by one position.\n        <\/p>\n\n        <p>\n            Return <i>the max sliding window<\/i>.\n        <\/p>\n\n                <h2>Examples:<\/h2>\n                <h5>Example 1:<\/h5>\n                <p><strong>Input:<\/strong> nums = [1,3,-1,-3,5,3,6,7], k = 3<\/p>\n                <p><strong>Output:<\/strong> [3,3,5,5,6,7]<\/p>\n                <p>\n                  <strong>Explanation:<\/strong>\n<pre>\nWindow position                Max\n---------------               -----\n[1  3  -1] -3  5  3  6  7       3\n 1 [3  -1  -3] 5  3  6  7       3\n 1  3 [-1  -3  5] 3  6  7       5\n 1  3  -1 [-3  5  3] 6  7       5\n 1  3  -1  -3 [5  3  6] 7       6\n 1  3  -1  -3  5 [3  6  7]      7\n                <\/p>\n<\/pre>\n                <h5>Example 2:<\/h5>\n                <p><strong>Input:<\/strong> nums = [1], k = 1<\/p>\n                <p><strong>Output:<\/strong> [1]<\/p>\n                \n                    <h2>Constraints:<\/h2>\n                    <ul>\n                      <li><code>1 <= nums.length <= 10<sup>5<\/sup><\/code><\/li>\n\n                      <li><code>-10<sup>4<\/sup> <= nums[i] <= 10<sup>5<\/sup><\/code><\/li>\n                      <li><code>-10<sup>4<\/sup> <= nums[i] <= 10<sup>4<\/sup><\/code><\/li>\n                      <li><code>1 <= k <= nums.length<\/code><\/li>\n                    <\/ul>\n\n                <h2>Approach<\/h2>\n                <ul>\n                    <li><strong>Initialize:<\/strong>    \n                        <ul>\n                            <li><code>res[]<\/code> to store result.<\/li>\n                            <li><code>q[]<\/code> to store elements in decreasing order (front always holds the max).<\/li>\n                            <li>Two pointers: <code>i<\/code> (window start) and <code>j<\/code> (window end).<\/li>\n                        <\/ul>\n                    <\/li>\n\n                    <li><strong>Traverse the array:<\/strong>\n                    <ul>\n                        <li>Remove elements from the back of the queue if they are smaller than current <code>(arr[j])<\/code>, since they can't be max.<\/li>\n                        <li>Add <code>arr[j]<\/code> to the queue.<\/li>\n                        <li>When window size k is hit <code>(j >= k - 1)<\/code>:\n                        <ul>\n                            <li>Push the <strong>front of the queue<\/strong> to <code>res<\/code> (it's the current max).<\/li>\n                            <li>If the element going out of the window (arr[i]) is equal to the front of the queue, <code>remove it<\/code> <code>(q.shift())<\/code>.<\/li>\n                            <li>Move window ahead by incrementing <code>i<\/code>.<\/li>\n                        <\/ul>\n                        <\/li>\n                    <\/ul>\n                    <\/li>\n\n                    <li><strong>Return<\/strong> the result array res.<\/li>\n                <\/ul>\n\n                <h2>Time Complexity:<\/h2>\n                <li>\n                  <p><strong>Time Complexity = O(n)<\/strong>\n                  <\/li>\n                <h2>Space Complexity:<\/h2>\n                <li>\n                  <p><strong>Space Complexity = O(n)<\/strong><\/p>\n                <\/li>\n\n<h2>Dry Run<\/h2> <div style=\"background: #f9f9f9; border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0;\"> <p><strong>Input:<\/strong> <code>arr = [1,3,-1,-3,5,3,6,7], k = 3<\/code><\/p> <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\"> Initialize: \u2192 res = [] \u2192 q = [] \u2192 i = 0, j = 0\nStart sliding window loop:\nj = 0 \u2192 arr[j] = 1\n\u2192 q = [] (empty)\n\u2192 push 1 \u2192 q = [1]\n\nj = 1 \u2192 arr[j] = 3\n\u2192 3 > 1 \u2192 pop 1 \u2192 q = []\n\u2192 push 3 \u2192 q = [3]\n\nj = 2 \u2192 arr[j] = -1\n\u2192 -1 not greater than 3 \u2192 push -1 \u2192 q = [3, -1]\n\u2192 j >= k-1 (2 >= 2): window formed\n\u2192 push q[0] = 3 to res \u2192 res = [3]\n\u2192 arr[i] == q[0]? \u2192 arr[0] = 1 \u2260 3 \u2192 don't shift q\n\u2192 i++\n\nj = 3 \u2192 arr[j] = -3\n\u2192 -3 not greater than -1 \u2192 push -3 \u2192 q = [3, -1, -3]\n\u2192 j >= k-1 \u2192 push q[0] = 3 \u2192 res = [3, 3]\n\u2192 arr[1] = 3 == q[0] \u2192 shift q \u2192 q = [-1, -3]\n\u2192 i++\n\nj = 4 \u2192 arr[j] = 5\n\u2192 5 > -3 \u2192 pop -3\n\u2192 5 > -1 \u2192 pop -1\n\u2192 q = [] \u2192 push 5 \u2192 q = [5]\n\u2192 j >= k-1 \u2192 push q[0] = 5 \u2192 res = [3, 3, 5]\n\u2192 arr[2] = -1 \u2260 5 \u2192 don't shift q\n\u2192 i++\n\nj = 5 \u2192 arr[j] = 3\n\u2192 3 not greater than 5 \u2192 push 3 \u2192 q = [5, 3]\n\u2192 j >= k-1 \u2192 push q[0] = 5 \u2192 res = [3, 3, 5, 5]\n\u2192 arr[3] = -3 \u2260 5 \u2192 don't shift q\n\u2192 i++\n\nj = 6 \u2192 arr[j] = 6\n\u2192 6 > 3 \u2192 pop 3\n\u2192 6 > 5 \u2192 pop 5 \u2192 q = []\n\u2192 push 6 \u2192 q = [6]\n\u2192 j >= k-1 \u2192 push q[0] = 6 \u2192 res = [3, 3, 5, 5, 6]\n\u2192 arr[4] = 5 \u2260 6 \u2192 don't shift q\n\u2192 i++\n\nj = 7 \u2192 arr[j] = 7\n\u2192 7 > 6 \u2192 pop 6 \u2192 q = []\n\u2192 push 7 \u2192 q = [7]\n\u2192 j >= k-1 \u2192 push q[0] = 7 \u2192 res = [3, 3, 5, 5, 6, 7]\n\u2192 arr[5] = 3 \u2260 7 \u2192 don't shift q\n\u2192 i++\n\nEnd of loop\n\n<\/pre> <p><strong>Output:<\/strong> <code>Result: [3, 3, 5, 5, 6, 7]<\/code><\/p> <\/div>\n        <h2>Visualisation:<\/h2>\n        <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-20-at-5.54.59\u202fPM.png\" alt=\"longest\" \/>\n    <\/div>\n    \n\n    <div class=\"wp_blog_code-tabs-container\">\n        <div class=\"wp_blog_code-tabs-header\">\n            <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n        <\/div>\n\n        <!-- JavaScript -->\n        <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n            <pre><code class=\"language-javascript\">\nvar maxSlidingWindow = function(arr, k) {\n  let res = [];\n  let q = [];\n\n  let i = j = 0;\n  while (j < arr.length) {\n    while (q.length &#038;&#038; arr[j] > q[q.length - 1]) {\n      q.pop();\n    }\n    q.push(arr[j]);\n\n    if (j >= k - 1) {\n      res.push(q[0]);\n      if (arr[i] == q[0]) q.shift();\n      ++i;\n    }\n    ++j;\n  }\n  return res;\n};\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- Python -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n            <pre><code class=\"language-python\">\nfrom collections import deque\ndef maxSlidingWindow(arr, k):\n    res = []\n    q = deque()\nsc\n    i = j = 0\n    while j < len(arr):\n        while q and arr[j] > q[-1]:\n            q.pop()\n        q.append(arr[j])\n\n        if j >= k - 1:\n            res.append(q[0])\n            if arr[i] == q[0]:\n                q.popleft()\n            i += 1\n        j += 1\n\n    return res\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- Java -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n            <pre><code class=\"language-java\">\nimport java.util.*;\n\npublic class Solution {\n    public static List<Integer> maxSlidingWindow(int[] arr, int k) {\n        List<Integer> res = new ArrayList<>();\n        Deque<Integer> q = new LinkedList<>();\n        int i = 0, j = 0;\n        while (j < arr.length) {\n            while (!q.isEmpty() &#038;&#038; arr[j] > q.peekLast()) {\n                q.pollLast();\n            }\n            q.offerLast(arr[j]);\n\n            if (j >= k - 1) {\n                res.add(q.peekFirst());\n                if (arr[i] == q.peekFirst()) q.pollFirst();\n                i++;\n            }\n            j++;\n        }\n        return res;\n    }\n}\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- C++ -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n            <pre><code class=\"language-cpp\">\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;deque&gt;\nusing namespace std;\n\nvector<int> maxSlidingWindow(vector<int>& arr, int k) {\n    vector<int> res;\n    deque<int> q;\n    int i = 0, j = 0;\n\n    while (j < arr.size()) {\n        while (!q.empty() &#038;&#038; arr[j] > q.back()) {\n            q.pop_back();\n        }\n        q.push_back(arr[j]);\n\n        if (j >= k - 1) {\n            res.push_back(q.front());\n            if (arr[i] == q.front()) q.pop_front();\n            i++;\n        }\n        j++;\n    }\n    return res;\n}\n\n    <\/code><\/pre>\n        <\/div>\n\n        <!-- C -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n            <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#define MAX 10000\n\nvoid maxSlidingWindow(int arr[], int n, int k) {\n    int res[MAX];\n    int q[MAX], front = 0, rear = -1;\n    int i = 0, j = 0, idx = 0;\n    while (j < n) {\n        while (rear >= front && arr[j] > q[rear]) {\n            rear--;\n        }\n        q[++rear] = arr[j];\n\n        if (j >= k - 1) {\n            res[idx++] = q[front];\n            if (arr[i] == q[front]) front++;\n            i++;\n        }\n        j++;\n    }\n    for (int m = 0; m < idx; m++)\n        printf(\"%d \", res[m]);\n}\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- C# -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n            <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\nclass Solution {\n    public static IList<int> MaxSlidingWindow(int[] arr, int k) {\n        List<int> res = new List<int>();\n        LinkedList<int> q = new LinkedList<int>();\n        int i = 0, j = 0;\n        while (j < arr.Length) {\n            while (q.Count > 0 && arr[j] > q.Last.Value) {\n                q.RemoveLast();\n            }\n            q.AddLast(arr[j]);\n            if (j >= k - 1) {\n                res.Add(q.First.Value);\n                if (arr[i] == q.First.Value) q.RemoveFirst();\n                i++;\n            }\n            j++;\n        }\n        return res;\n    }\n}\n       <\/code><\/pre>\n        <\/div>\n    <\/div>\n<\/div>\n\n<script>\n    document.addEventListener(\"DOMContentLoaded\", () => {\n        const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n        const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n        buttons.forEach((button) => {\n            button.addEventListener(\"click\", () => {\n                const lang = button.getAttribute(\"data-lang\");\n\n                buttons.forEach((btn) => btn.classList.remove(\"active\"));\n                contents.forEach((content) =>\n                    content.classList.remove(\"active\")\n                );\n\n                button.classList.add(\"active\");\n                document\n                    .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n                    .classList.add(\"active\");\n            });\n        });\n    });\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[322,176,175,211,174,172,173],"tags":[],"class_list":["post-8083","post","type-post","status-publish","format-standard","category-algorithms-and-data-structures","category-csharp","category-cplusplus","category-data-structures","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8083","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=8083"}],"version-history":[{"count":2,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8083\/revisions"}],"predecessor-version":[{"id":8103,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8083\/revisions\/8103"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=8083"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=8083"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=8083"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}