DATA STRUCTURES PROGRAM • STACKS & EXPRESSIONS

Implement a Stack with Constant-Time Minimum

Learn how to implement a stack with constant-time minimum using a clear C program.

BeginnerStackLIFOpush/pop

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Minimum = 1
After pop, minimum = 1

COMPLETE C PROGRAM

Complete C implementation

dsa-min-stack.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

#define CAPACITY 50
struct Stack { int values[CAPACITY]; int top; };
void stack_init(struct Stack *stack) { stack->top = -1; }
int stack_empty(const struct Stack *stack) { return stack->top < 0; }
void stack_push(struct Stack *stack, int value)
{
    if (stack->top + 1 >= CAPACITY) { puts("Stack overflow."); exit(EXIT_FAILURE); }
    stack->values[++stack->top] = value;
}
int stack_pop(struct Stack *stack)
{
    if (stack_empty(stack)) { puts("Stack underflow."); exit(EXIT_FAILURE); }
    return stack->values[stack->top--];
}
int stack_peek(const struct Stack *stack)
{
    if (stack_empty(stack)) { puts("Stack is empty."); exit(EXIT_FAILURE); }
    return stack->values[stack->top];
}

int main(void)
{
    int values[] = {5, 2, 8, 1, 4};
    struct Stack data, minimums;
    stack_init(&data); stack_init(&minimums);
    for (int index = 0; index < 5; index++) {
        stack_push(&data, values[index]);
        if (stack_empty(&minimums) || values[index] <= stack_peek(&minimums))
            stack_push(&minimums, values[index]);
    }
    printf("Minimum = %d\n", stack_peek(&minimums));
    int removed = stack_pop(&data);
    if (removed == stack_peek(&minimums)) stack_pop(&minimums);
    printf("After pop, minimum = %d\n", stack_peek(&minimums));
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Minimum = 1
After pop, minimum = 1
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Maintain a second stack containing the minimum values active at each depth.
  3. Display the computed result.

Maintain a second stack containing the minimum values active at each depth.

EFFICIENCY

Time and space complexity

Time complexity

O(1) per operation

Auxiliary space

O(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.