{"id":22513566,"url":"https://github.com/emahtab/sliding-window-maximum","last_synced_at":"2026-03-19T23:02:44.201Z","repository":{"id":79525797,"uuid":"276719589","full_name":"eMahtab/sliding-window-maximum","owner":"eMahtab","description":"Find Max within a fixed size window","archived":false,"fork":false,"pushed_at":"2025-01-18T03:10:57.000Z","size":48,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-24T23:02:08.693Z","etag":null,"topics":["leetcode","monotonic-queue","sliding-window"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eMahtab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-07-02T18:32:53.000Z","updated_at":"2025-01-18T03:10:58.000Z","dependencies_parsed_at":"2025-01-18T03:36:46.243Z","dependency_job_id":null,"html_url":"https://github.com/eMahtab/sliding-window-maximum","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/eMahtab/sliding-window-maximum","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fsliding-window-maximum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fsliding-window-maximum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fsliding-window-maximum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fsliding-window-maximum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eMahtab","download_url":"https://codeload.github.com/eMahtab/sliding-window-maximum/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fsliding-window-maximum/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29016669,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-02T16:17:30.374Z","status":"ssl_error","status_checked_at":"2026-02-02T15:58:50.469Z","response_time":58,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["leetcode","monotonic-queue","sliding-window"],"created_at":"2024-12-07T03:13:26.498Z","updated_at":"2026-02-02T18:04:39.172Z","avatar_url":"https://github.com/eMahtab.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Sliding Window Maximum\n## https://leetcode.com/problems/sliding-window-maximum\n\nYou 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.\n\nReturn the max sliding window.\n```java\nExample 1:\n\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput: [3,3,5,5,6,7]\nExplanation: \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\nExample 2:\n\nInput: nums = [1], k = 1\nOutput: [1]\n```\n\n### Constraints:\n\n1. 1 \u003c= nums.length \u003c= 105\n2. -104 \u003c= nums[i] \u003c= 104\n3. 1 \u003c= k \u003c= nums.length\n\n# Implementation 1 : Naive : Calculate max for each window of length k (TLE)\n```java\nclass Solution {\n    public int[] maxSlidingWindow(int[] nums, int k) {\n        int[] result = new int[nums.length - k + 1];\n\n        int index = 0;\n        \n        for(int i = 0; i \u003c= nums.length - k; i++) {\n            result[index++] = getMax(nums,i, i+k-1);    \n        }\n        return result;\n    }\n    \n    private int getMax(int[] nums, int start, int end) {\n        int max = nums[start];\n        for(int i = start + 1; i \u003c= end; i++) {\n           max = Math.max(max, nums[i]);   \n        }\n        return max;\n    }\n}\n```\n# Implementation 2 : Next Greater Element approach\n```java\nclass Solution {\n    public int[] maxSlidingWindow(int[] nums, int k) {\n        int[] result = new int[nums.length - k + 1];\n        // Next greater element\n        int[] ngeI = new int[nums.length];\n        ngeI[nums.length - 1] = nums.length;\n        Stack\u003cInteger\u003e stack = new Stack\u003c\u003e();\n        stack.push(nums.length - 1);\n        for(int i = nums.length - 2; i \u003e= 0; i--) {\n            while(!stack.isEmpty() \u0026\u0026 nums[stack.peek()] \u003c= nums[i]) {\n                stack.pop();\n            }\n            if(stack.isEmpty()) {\n                ngeI[i] = nums.length;\n            } else {\n                ngeI[i] = stack.peek();\n            }\n            stack.push(i);\n        }\n        int index = 0;\n        for(int i = 0; i \u003c= nums.length - k; i++) {\n            int j = i;\n            while(ngeI[j] \u003c i + k) {\n                j = ngeI[j];\n            }\n            result[index++] = nums[j];\n        }\n        return result;\n    }\n}\n```\n### Sliding Window Approach with Monotonic Queue\nThe idea is to keep the maximum number in the sliding window at the front of the Deque and the `possible maximum` numbers at the rear end (last) of the queue. The Deque would have numbers sorted in descending order, front having the maximum number and rear would have the smallest in the current window.\n\n1. As we iterate over the array if `num[i]` is greater than the smallest number of current window than we start removing the numbers as long as `num[i]` is greater than number in the window.\n\n2. Also we add the index of current number in Deque as this number could be `possible maximum` as the window slides to the right.\n\nWe could have tried to use Stack or PriorityQueue to keep track of maximum in the current window, but we don't only need to track maximum number in the current window but also other numbers `(possible maximum)` which are less than maximum number in the current window. Because as we move to the next window, these `possible maximum` numbers might become the maximum number in that window.\n\n#### Choosing the right Data Structure : Double Ended Queue (Deque)\nIf we use Stack, we can only get access to the top element, for accessing other elements we would have to pop the elements from the stack and would have to push it back to stack.\n\nSimilarly if we use PriorityQueue we can only get access to the min or max element which is at the top of heap, for accessing other elements we would have to remove elements from the heap and would have to push it back to heap.\n\nA Double ended Queue allows us to perform operation on both the ends of the data structure and we can easily access the elements in Deque. \n\n**We could have used Doubly Linked List as well, in Java LinkedList class implements the Deque interface and we can easily perform operations at both the end of LinkedList.**\n\n\nhttps://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html\n\nhttps://docs.oracle.com/javase/8/docs/api/java/util/Deque.html\n\n\nIn Java LinkedList and Deque gives us methods e.g. **addFirst(), addLast(), offerFirst(), offerLast(), removeFirst(), removeLast(), peekFirst(), peekLast(), pollFirst(), pollLast()** to easily access the front/rear element and also start traversal from the front or rear.\n\n## Notes :\n1. We store the index `i` in Deque and not `num[i]`, this is because we also have to remove numbers from the Deque as window slides to the right. We can check if index is out of current window we remove the number.\n\n2. For given window of K, remember we don't try to store k elements in the Deque, rather we just need to keep the maximum number at the front of Deque and add the current number at the rear end of Deque. And when we remove element from Deque we start from the rear end of Deque.\n\n# Implementation 3a : Using Deque, O(n), putting index into dequeue\n\n```java\nclass Solution {\n    public int[] maxSlidingWindow(int[] nums, int k) {\n        if(nums == null || nums.length == 0 || k \u003e nums.length)\n            return new int[0];\n        \n        int[] result = new int[nums.length - k + 1];\n        Deque\u003cInteger\u003e dq = new ArrayDeque\u003c\u003e();\n        int index = 0;\n        while(index \u003c nums.length) {\n            if(!dq.isEmpty() \u0026\u0026 dq.peekFirst() == index - k)\n                dq.pollFirst();\n            \n            while(!dq.isEmpty() \u0026\u0026 nums[index] \u003e nums[dq.peekLast()])\n                dq.pollLast();\n            \n            dq.offerLast(index);\n            if(index \u003e= k - 1) {\n                result[index-k+1] = nums[dq.peekFirst()];\n            }\n            index++;\n        }\n        return result;\n    }\n}\n```\n\n## Implementation 3aa : Using LinkedList, O(n), putting index into dequeue\n\n```java\nclass Solution {\n    public int[] maxSlidingWindow(int[] nums, int k) {\n        if(nums == null || nums.length \u003c k)\n           return new int[0];\n\n        int[] result = new int[nums.length - k + 1]; \n        Deque\u003cInteger\u003e deque = new LinkedList\u003c\u003e();\n        int index = 0;\n        for(int i = 0; i \u003c nums.length; i++) {\n            if(!deque.isEmpty() \u0026\u0026 deque.peekFirst() == i -k)\n                deque.pollFirst();\n            \n            while(!deque.isEmpty() \u0026\u0026 nums[i] \u003e nums[deque.peekLast()])\n                 deque.pollLast(); \n\n            deque.offerLast(i);       \n            if(i \u003e= k - 1) {\n                result[index++] = nums[deque.peekFirst()];\n            }       \n        }\n        return result;\n    }\n}\n```\n# Implementation 3b : Deque , O(n), putting number in Deque\n```java\nclass Solution {\n    public int[] maxSlidingWindow(int[] nums, int k) {\n        Deque\u003cInteger\u003e deque = new ArrayDeque\u003c\u003e();\n        int n = nums.length;\n        int[] result = new int[n-k+1];\n        int index = 0;\n        int i = 0;\n        while(index \u003c n) {\n            if(!deque.isEmpty() \u0026\u0026 (index \u003e k-1 \u0026\u0026 deque.peekFirst() == nums[index-k]))\n                deque.pollFirst();\n\n            while(!deque.isEmpty() \u0026\u0026 nums[index] \u003e deque.peekLast())\n                deque.pollLast();\n\n            deque.offerLast(nums[index]);\n\n            if(index \u003e= k-1){\n                result[i++] = deque.peekFirst();\n            }\n            index++;        \n        }\n        return result;\n    }\n}\n```\n# References :\nhttps://docs.oracle.com/javase/8/docs/api/java/util/Deque.html\n\nhttps://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html\n\nhttps://www.youtube.com/watch?v=fbkvdWUS5Ic\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fsliding-window-maximum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femahtab%2Fsliding-window-maximum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fsliding-window-maximum/lists"}