ADVANCED DATA STRUCTURES PROGRAM • LEVEL 21 — PLACEMENT-ORIENTED STRUCTURES
Answer Static Range Minimum Queries with a Sparse Table
Learn how to answer static range minimum queries with a sparse table using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Minimum = 0
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int values[]={7,2,3,0,5,10,3,12,18},table[4][9],logs[10]={0};for(int i=2;i<=9;i++)logs[i]=logs[i/2]+1;for(int i=0;i<9;i++)table[0][i]=values[i];for(int level=1;(1<<level)<=9;level++)for(int i=0;i+(1<<level)<=9;i++){int a=table[level-1][i],b=table[level-1][i+(1<<(level-1))];table[level][i]=a<b?a:b;}int left=2,right=6,level=logs[right-left+1],a=table[level][left],b=table[level][right-(1<<level)+1];printf("Minimum = %d\n",a<b?a:b);return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Minimum = 0
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Precompute minima for power-of-two blocks and cover a query with two overlapping blocks.
- Display the computed result.
Precompute minima for power-of-two blocks and cover a query with two overlapping blocks.
EFFICIENCY
Time and space complexity
Time complexity
O(n log n) build, O(1) query
Auxiliary space
O(n log n)
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.
