new_connection #191007
-
Discussion TypeProduct Feedback Discussion ContentGiven an array and window size k, return max in each window. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
|
💬 Your Product Feedback Has Been Submitted 🎉 Thank you for taking the time to share your insights with us! Your feedback is invaluable as we build a better GitHub experience for all our users. Here's what you can expect moving forward ⏩
Where to look to see what's shipping 👀
What you can do in the meantime 💻
As a member of the GitHub community, your participation is essential. While we can't promise that every suggestion will be implemented, we want to emphasize that your feedback is instrumental in guiding our decisions and priorities. Thank you once again for your contribution to making GitHub even better! We're grateful for your ongoing support and collaboration in shaping the future of our platform. ⭐ |
Beta Was this translation helpful? Give feedback.
-
|
🧠 Idea: Maintain max of each window of size k. ❌ Brute Force 👉 Each element added & removed once ⚡ Complexity 👉 Deque is optimal because it avoids re-processing elements 🧪 Example |
Beta Was this translation helpful? Give feedback.
-
|
Hi @mrenemy999-os, this is the Sliding Window Maximum problem. Here are a few approaches: Solution 1: Deque (Optimal - O(n))from collections import deque
def max_sliding_window(nums, k):
if not nums:
return []
result = []
dq = deque() # stores indices
for i, num in enumerate(nums):
# Remove indices outside current window
while dq and dq[0] < i - k + 1:
dq.popleft()
# Remove smaller elements from back
while dq and nums[dq[-1]] < num:
dq.pop()
dq.append(i)
# Add to result when window is fully formed
if i >= k - 1:
result.append(nums[dq[0]])
return resultSolution 2: Brute Force (O(n*k) — Not efficient for large arrays)def max_sliding_window_bruteforce(nums, k):
if not nums:
return []
result = []
for i in range(len(nums) - k + 1):
result.append(max(nums[i:i+k]))
return resultExamplenums = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(max_sliding_window(nums, k))
# Output: [3, 3, 5, 5, 6, 7]Complexity
ExplanationThe deque approach maintains elements in decreasing order. At each step:
|
Beta Was this translation helpful? Give feedback.
🧠 Idea:
Maintain max of each window of size k.
❌ Brute Force
Check max for every window
Time: O(n * k) → slow
🚀 Optimal (Deque)
💡 Why deque works?
Stores indices in decreasing order
Front = maximum of current window
Remove:
Out-of-window elements (from front)
Smaller elements (from back)
👉 Each element added & removed once
⚡ Complexity
Time: O(n) (amortized)
Space: O(k)
🔁 Heap (Alternative)
Use max heap
Time: O(n log k)
Slower due to log factor
Also need lazy deletion
🧠 Key Insight
👉 Deque is optimal because it avoids re-processing elements
👉 Maintains only useful candidates for max
🧪 Example
nums = [1,3,-1,-3,5,3,6,7], k=3
output = [3,3,5,5,6,7]