Monotonic Queue Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Monotonic Queue runs in O(n) time and O(n) space, in Go as in every other language.
- ✓No deque. container/list would work but boxes every element into an any and allocates a node each time.
- ✓Hold indices in a slice, evict the back by re-slicing dq = dq[:len(dq)-1] and the front by advancing dq = dq[1:].
- ✓The Go trap: Advancing the front with dq = dq[1:] moves the slice header forward but never releases the backing array, and the array is only freed when the last slice referencing it becomes garbage.
- ✓Re-slicing is a pointer and length adjustment with no allocation and no copying, which is why the slice form comfortably beats container/list here.
What Monotonic Queue actually is
Monotonic Queue in Go: what you actually reach for
Go implementation
package monotonic
// SlidingWindowMax returns the maximum of every window of size k. O(n).
func SlidingWindowMax(nums []int, k int) []int {
if k <= 0 || len(nums) == 0 {
return nil
}
// Never holds more than k indices.
dq := make([]int, 0, k)
out := make([]int, 0, len(nums)-k+1)
for i, n := range nums {
// Front eviction: re-slicing is O(1). Note this keeps the original
// backing array alive; the fixed-buffer version below avoids that.
if len(dq) > 0 && dq[0] <= i-k {
dq = dq[1:]
}
// Back eviction.
for len(dq) > 0 && nums[dq[len(dq)-1]] <= n {
dq = dq[:len(dq)-1]
}
dq = append(dq, i)
if i >= k-1 {
out = append(out, nums[dq[0]])
}
}
return out
}
// SlidingWindowMaxRing uses one fixed buffer with head/tail indices, so
// nothing is pinned and nothing is reallocated for the whole stream.
func SlidingWindowMaxRing(nums []int, k int) []int {
if k <= 0 || len(nums) == 0 {
return nil
}
buf := make([]int, k)
head, tail := 0, 0 // [head, tail) is the live window
out := make([]int, 0, len(nums)-k+1)
for i, n := range nums {
if tail > head && buf[head%k] <= i-k {
head++
}
for tail > head && nums[buf[(tail-1)%k]] <= n {
tail--
}
buf[tail%k] = i
tail++
if i >= k-1 {
out = append(out, nums[buf[head%k]])
}
}
return out
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Monotonic Queue?
No deque. container/list would work but boxes every element into an any and allocates a node each time. The idiomatic structure is a slice used from both ends.
What is the most common Go mistake when implementing Monotonic Queue?
Advancing the front with dq = dq[1:] moves the slice header forward but never releases the backing array, and the array is only freed when the last slice referencing it becomes garbage. Over a long stream that means the original allocation is pinned for the life of the loop even though the live window is tiny. Preallocating a buffer of exactly k and reusing it with explicit head and tail indices avoids the issue entirely, and is the form you will find in production Go.
How does Monotonic Queue actually perform in Go?
Re-slicing is a pointer and length adjustment with no allocation and no copying, which is why the slice form comfortably beats container/list here. make([]int, 0, k) bounds the allocation to the window, and the compiler usually eliminates the bounds checks in the inner loop. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.