4. Identify the error in this Go code snippet using container/list as a deque:
package main
import (
"container/list"
"fmt"
)
func main() {
d := list.New()
d.PushFront(1)
d.Remove(d.Back())
fmt.Println(d.Back().Value)
}
medium
A. Using PushFront instead of PushBack
B. Not initializing the list with make()
C. Printing d.Back().Value without converting to string
D. Calling Remove on d.Back() before checking if d.Back() is nil
Solution
Step 1: Understand Remove and Back usage
d.Remove(d.Back()) removes the last element; after removal, d.Back() may be nil if list is empty.
Step 2: Check the print statement
fmt.Println(d.Back().Value) accesses Value of d.Back() without checking if d.Back() is nil, causing runtime panic if nil.
Final Answer:
Calling Remove on d.Back() before checking if d.Back() is nil -> Option D
Quick Check:
Check nil before accessing Back() after Remove [OK]
Hint: Check nil after Remove before accessing Back() [OK]
Common Mistakes:
Ignoring nil check after removal
Confusing PushFront and PushBack
Thinking fmt.Println needs string conversion
5. You want to implement a sliding window maximum using a deque in Go. Which deque operation sequence correctly maintains the window elements in decreasing order from front to rear?
// Assume d is a deque of indices
for i := 0; i < len(nums); i++ {
for d.Len() > 0 && nums[d.Back().Value.(int)] <= nums[i] {
d.Remove(d.Back())
}
d.PushBack(i)
if d.Front().Value.(int) <= i - k {
d.Remove(d.Front())
}
}
hard
A. Remove from back while current element is greater or equal, then add current index at back
B. Remove from front while current element is smaller, then add current index at front
C. Add current index at front without removals
D. Remove from back while current element is smaller, then add current index at front
Solution
Step 1: Understand sliding window max logic
We remove smaller or equal elements from back to keep deque decreasing, then add current index at back.
Step 2: Remove indices out of window from front
If front index is out of current window (i - k), remove it from front to maintain window size.
Final Answer:
Remove from back while current element is greater or equal, then add current index at back -> Option A
Quick Check:
Sliding window max uses back removals and back insertions [OK]
Hint: Remove smaller from back, add new at back for max window [OK]
Common Mistakes:
Removing from front instead of back for smaller elements
Adding new elements at front incorrectly
Not removing out-of-window indices
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.