Skip to content
Discussion options

You must be logged in to vote

🧠 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]

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by mrenemy999-os
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Discussions GitHub Discussions is a collaborative communication feature Product Feedback Share your thoughts and suggestions on GitHub features and improvements Welcome 🎉 Used to greet and highlight first-time discussion participants. Welcome to the community! source:ui Discussions created via Community GitHub templates
3 participants