|
| 1 | +--- |
| 2 | +id: sliding-window-maximum |
| 3 | +title: Sliding Window Maximum |
| 4 | +sidebar_label: 239 -Sliding Window Maximum |
| 5 | +tags: |
| 6 | +- Array |
| 7 | +- Queue |
| 8 | +- Sliding Window |
| 9 | +- Heap (Priority Queue) |
| 10 | +- Monotonic Queue |
| 11 | + |
| 12 | +description: "This is a solution to the Sliding Window Maximum problem on LeetCode." |
| 13 | +--- |
| 14 | + |
| 15 | +## Problem Description |
| 16 | +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. |
| 17 | + |
| 18 | +Return the max sliding window. |
| 19 | + |
| 20 | +### Examples |
| 21 | + |
| 22 | +**Example 1:** |
| 23 | + |
| 24 | +``` |
| 25 | +Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 |
| 26 | +Output: [3,3,5,5,6,7] |
| 27 | +Explanation: |
| 28 | +Window position Max |
| 29 | +--------------- ----- |
| 30 | +[1 3 -1] -3 5 3 6 7 3 |
| 31 | + 1 [3 -1 -3] 5 3 6 7 3 |
| 32 | + 1 3 [-1 -3 5] 3 6 7 5 |
| 33 | + 1 3 -1 [-3 5 3] 6 7 5 |
| 34 | + 1 3 -1 -3 [5 3 6] 7 6 |
| 35 | + 1 3 -1 -3 5 [3 6 7] 7 |
| 36 | +``` |
| 37 | + |
| 38 | +**Example 2:** |
| 39 | +``` |
| 40 | +Input: nums = [1], k = 1 |
| 41 | +Output: [1] |
| 42 | +``` |
| 43 | + |
| 44 | +### Constraints |
| 45 | +- `1 <= nums.length <= 10^5` |
| 46 | +- `10^4 <= nums[i] <= 10^4` |
| 47 | +- `1 <= k <= nums.length` |
| 48 | + |
| 49 | +## Solution for Sliding Window Maximum Problem |
| 50 | +### Approach |
| 51 | +##### Sliding Window Approach: |
| 52 | +- The sliding window technique involves maintaining a window of fixed size (k) as it slides from the beginning to the end of the array. |
| 53 | +This allows us to efficiently compute the desired result for each window without redundant computations. |
| 54 | +##### HashMap Usage: |
| 55 | +- A hashmap (or hash table) is utilized to keep track of elements within the current window and their frequencies (or counts). |
| 56 | +The hashmap helps in quickly determining the maximum element within the current window without having to scan the entire window repeatedly. |
| 57 | +##### Initialization: |
| 58 | +-Initialize two pointers, left and right, to define the current window. Initially, set both pointers to the beginning of the array. |
| 59 | +##### Building the Initial Window: |
| 60 | +- Extend the right pointer to expand the window until its size reaches k. During this expansion: |
| 61 | +Update the hashmap to include the frequency of each element in the current window. |
| 62 | +##### Maintaining the Hashmap: |
| 63 | +- As you slide the window (right pointer moves one step to the right), update the hashmap: |
| 64 | +- Increment the count of the element pointed by right. |
| 65 | +- Adjust the hashmap to ensure it reflects the elements and their counts within the current window. |
| 66 | +##### Finding the Maximum: |
| 67 | + |
| 68 | +- Once the window size equals k, retrieve the maximum value from the hashmap. Depending on the requirement (maximum or minimum), this can be determined efficiently: |
| 69 | +- For maximum: Iterate through the hashmap (or use additional data structures like max heap) to find the maximum element. |
| 70 | +- For minimum: Similarly, find the minimum element within the hashmap. |
| 71 | +##### Adjusting the Window: |
| 72 | + |
| 73 | +- Slide the window to the right (left pointer moves one step to the right): |
| 74 | +- Decrement the count of the element pointed by left. |
| 75 | +- Remove elements from the hashmap if their count drops to zero to maintain accuracy in the calculation. |
| 76 | +##### Output the Result: |
| 77 | +- Store or directly process the result for each window (e.g., store the maximum value found for each window). |
| 78 | + |
| 79 | +- Repeat Until Completion: |
| 80 | +- Continue this process until the right pointer has traversed the entire array. |
| 81 | +<Tabs> |
| 82 | + <TabItem value="Solution" label="Solution"> |
| 83 | + |
| 84 | + #### Implementation |
| 85 | + ```jsx live |
| 86 | + function Solution(arr) { |
| 87 | + var maxSlidingWindow = function(nums, k) { |
| 88 | + let maxQueue = []; |
| 89 | + let result = []; |
| 90 | + |
| 91 | + for (let i = 0; i < nums.length; i++) { |
| 92 | + // Remove elements from maxQueue that are out of the current window |
| 93 | + while (maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < nums[i]) { |
| 94 | + maxQueue.pop(); |
| 95 | + } |
| 96 | + |
| 97 | + // Add current element to maxQueue |
| 98 | + maxQueue.push(nums[i]); |
| 99 | + |
| 100 | + // Remove elements from maxQueue that are out of the current window range |
| 101 | + if (i >= k - 1) { |
| 102 | + result.push(maxQueue[0]); |
| 103 | + if (nums[i - k + 1] === maxQueue[0]) { |
| 104 | + maxQueue.shift(); |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + return result; |
| 110 | +}; |
| 111 | + |
| 112 | + const input = [1,3,-1,-3,5,3,6,7] |
| 113 | + const k = 3 |
| 114 | + const output =maxSlidingWindow(input , k) |
| 115 | + return ( |
| 116 | + <div> |
| 117 | + <p> |
| 118 | + <b>Input: </b> |
| 119 | + {JSON.stringify(input)} |
| 120 | + </p> |
| 121 | + <p> |
| 122 | + <b>Output:</b> {output.toString()} |
| 123 | + </p> |
| 124 | + </div> |
| 125 | + ); |
| 126 | + } |
| 127 | + ``` |
| 128 | + |
| 129 | + #### Complexity Analysis |
| 130 | + |
| 131 | + - Time Complexity: $ O(n) $ because of traversing |
| 132 | + - Space Complexity: $ O(n) $ because of hashmap |
| 133 | + |
| 134 | + ## Code in Different Languages |
| 135 | + <Tabs> |
| 136 | + <TabItem value="JavaScript" label="JavaScript"> |
| 137 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 138 | + ```javascript |
| 139 | + var maxSlidingWindow = function(nums, k) { |
| 140 | + let maxQueue = []; |
| 141 | + let result = []; |
| 142 | + |
| 143 | + for (let i = 0; i < nums.length; i++) { |
| 144 | + // Remove elements from maxQueue that are out of the current window |
| 145 | + while (maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < nums[i]) { |
| 146 | + maxQueue.pop(); |
| 147 | + } |
| 148 | + |
| 149 | + // Add current element to maxQueue |
| 150 | + maxQueue.push(nums[i]); |
| 151 | + |
| 152 | + // Remove elements from maxQueue that are out of the current window range |
| 153 | + if (i >= k - 1) { |
| 154 | + result.push(maxQueue[0]); |
| 155 | + if (nums[i - k + 1] === maxQueue[0]) { |
| 156 | + maxQueue.shift(); |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + return result; |
| 162 | +}; |
| 163 | + |
| 164 | + ``` |
| 165 | + |
| 166 | + </TabItem> |
| 167 | + <TabItem value="TypeScript" label="TypeScript"> |
| 168 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 169 | + ```typescript |
| 170 | + function maxSlidingWindow(nums: number[], k: number): number[] { |
| 171 | + let maxQueue: number[] = []; |
| 172 | + let result: number[] = []; |
| 173 | + |
| 174 | + for (let i = 0; i < nums.length; i++) { |
| 175 | + // Remove elements from maxQueue that are out of the current window |
| 176 | + while (maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < nums[i]) { |
| 177 | + maxQueue.pop(); |
| 178 | + } |
| 179 | + |
| 180 | + // Add current element to maxQueue |
| 181 | + maxQueue.push(nums[i]); |
| 182 | + |
| 183 | + // Remove elements from maxQueue that are out of the current window range |
| 184 | + if (i >= k - 1) { |
| 185 | + result.push(maxQueue[0]); |
| 186 | + if (nums[i - k + 1] === maxQueue[0]) { |
| 187 | + maxQueue.shift(); |
| 188 | + } |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + return result; |
| 193 | +} |
| 194 | + ``` |
| 195 | + </TabItem> |
| 196 | + <TabItem value="Python" label="Python"> |
| 197 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 198 | + ```python |
| 199 | + function maxSlidingWindow(nums: number[], k: number): number[] { |
| 200 | + let maxQueue: number[] = []; |
| 201 | + let result: number[] = []; |
| 202 | + |
| 203 | + for (let i = 0; i < nums.length; i++) { |
| 204 | + // Remove elements from maxQueue that are out of the current window |
| 205 | + while (maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < nums[i]) { |
| 206 | + maxQueue.pop(); |
| 207 | + } |
| 208 | + |
| 209 | + // Add current element to maxQueue |
| 210 | + maxQueue.push(nums[i]); |
| 211 | + |
| 212 | + // Remove elements from maxQueue that are out of the current window range |
| 213 | + if (i >= k - 1) { |
| 214 | + result.push(maxQueue[0]); |
| 215 | + if (nums[i - k + 1] === maxQueue[0]) { |
| 216 | + maxQueue.shift(); |
| 217 | + } |
| 218 | + } |
| 219 | + } |
| 220 | + |
| 221 | + return result; |
| 222 | +} |
| 223 | +
|
| 224 | + ``` |
| 225 | + |
| 226 | + </TabItem> |
| 227 | + <TabItem value="Java" label="Java"> |
| 228 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 229 | + ```java |
| 230 | + import java.util.*; |
| 231 | +
|
| 232 | +class Solution { |
| 233 | + public int[] maxSlidingWindow(int[] nums, int k) { |
| 234 | + Deque<Integer> maxQueue = new LinkedList<>(); |
| 235 | + List<Integer> result = new ArrayList<>(); |
| 236 | + |
| 237 | + for (int i = 0; i < nums.length; i++) { |
| 238 | + // Remove elements from maxQueue that are out of the current window |
| 239 | + while (!maxQueue.isEmpty() && nums[maxQueue.peekLast()] < nums[i]) { |
| 240 | + maxQueue.pollLast(); |
| 241 | + } |
| 242 | + |
| 243 | + // Add current element to maxQueue |
| 244 | + maxQueue.offer(i); |
| 245 | + |
| 246 | + // Remove elements from maxQueue that are out of the current window range |
| 247 | + if (i >= k - 1) { |
| 248 | + result.add(nums[maxQueue.peekFirst()]); |
| 249 | + if (maxQueue.peekFirst() == i - k + 1) { |
| 250 | + maxQueue.pollFirst(); |
| 251 | + } |
| 252 | + } |
| 253 | + } |
| 254 | + |
| 255 | + // Convert List<Integer> to int[] |
| 256 | + return result.stream().mapToInt(Integer::intValue).toArray(); |
| 257 | + } |
| 258 | +} |
| 259 | +
|
| 260 | + ``` |
| 261 | + |
| 262 | + </TabItem> |
| 263 | + <TabItem value="C++" label="C++"> |
| 264 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 265 | + ```cpp |
| 266 | + class Solution { |
| 267 | +public: |
| 268 | + vector<int> maxSlidingWindow(vector<int>& nums, int k) { |
| 269 | + map<int,int>mp; |
| 270 | +
|
| 271 | + int i=0; |
| 272 | + int j=0; |
| 273 | + vector<int>ans; |
| 274 | + while(j<nums.size()) |
| 275 | + { |
| 276 | + mp[nums[j]]++; |
| 277 | + if(j-i+1<k) |
| 278 | + j++; |
| 279 | + else if(j-i+1==k) |
| 280 | + { |
| 281 | + auto it =mp.rbegin(); |
| 282 | + ans.push_back(it->first); |
| 283 | + j++; |
| 284 | + } |
| 285 | + else if(j-i+1>k) |
| 286 | + { |
| 287 | + while(j-i+1>k) |
| 288 | + { |
| 289 | + mp[nums[i]]--; |
| 290 | +
|
| 291 | + if(mp[nums[i]]==0)mp.erase(nums[i]); |
| 292 | +
|
| 293 | + i++; |
| 294 | + } |
| 295 | +
|
| 296 | + if(j-i+1==k) |
| 297 | + { |
| 298 | + auto it =mp.rbegin(); |
| 299 | + ans.push_back(it->first); |
| 300 | + } |
| 301 | +
|
| 302 | + j++; |
| 303 | +
|
| 304 | + } |
| 305 | + } |
| 306 | +
|
| 307 | + return ans; |
| 308 | + } |
| 309 | +}; |
| 310 | + ``` |
| 311 | +</TabItem> |
| 312 | +</Tabs> |
| 313 | + |
| 314 | + </TabItem> |
| 315 | +</Tabs> |
| 316 | + |
| 317 | +## References |
| 318 | + |
| 319 | +- **LeetCode Problem**: [Sliding Window Problem](https://leetcode.com/problems/sliding-window-maximum/description/) |
| 320 | + |
| 321 | +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/sliding-window-maximum/solutions) |
| 322 | + |
0 commit comments