ADVANCED DATA STRUCTURES PROGRAM • LEVEL 21 — PLACEMENT-ORIENTED STRUCTURES
Find Sliding-Window Maximums with a Deque
Learn how to find sliding-window maximums with a deque using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
3 3 5 5 6 7
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int values[]={1,3,-1,-3,5,3,6,7},deque[8],front=0,back=0,k=3;for(int i=0;i<8;i++){while(front<back&&deque[front]<=i-k)front++;while(front<back&&values[deque[back-1]]<=values[i])back--;deque[back++]=i;if(i>=k-1)printf("%d%c",values[deque[front]],i==7?'\n':' ');}return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
3 3 5 5 6 7
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Keep only useful indices in decreasing value order while removing indices outside the window.
- Display the computed result.
Keep only useful indices in decreasing value order while removing indices outside the window.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(k)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
