Validating Stack Pop Sequences with Capacity Constraints

Given a stack with a maximum capacity of M, and a sequence of numbers from 1 to N pushed in order, determine whether a given output sequence can be achieved through a series of push and pop operations.

The key insight is to simulate the stack operations: push elements from 1 to N in order, and whenever the top of the stack matches the next expected element in the target sequence, pop it. If at any point the stack exceeds capacity, or if we finish pushing all elements but cannot match the remaining target sequence, the sequence is invalid.

The algorithm uses a simulated stack (implemented as an array) to track pushed elements. For each number from 1 to N:

  • Push the number onto the stack if capacity allows.
  • While the stack is not empty and the top matches the next expected value in the target sequence, pop from the stack and advance the target pointer.
  • If the stack fills before all numbers are pushed, the sequence is impossible.

After processing all pushes, if the target sequence has been fully matched (i.e., the counter reaches N), the sequence is valid.

#define MAX_CAPACITY 1000

typedef struct { int data[MAX_CAPACITY]; int top; int capacity; } Stack;

int is_valid_pop_sequence(int target[], int max_capacity, int length) { Stack stack = { .top = -1, .capacity = max_capacity }; int target_index = 0;

for (int push_value = 1; push_value <= length; push_value++) {
    // Check if pushing would exceed capacity
    if (stack.top + 1 >= stack.capacity) {
        return 0;
    }

    // Push current value
    stack.data[++stack.top] = push_value;

    // Pop while top matches target sequence
    while (stack.top >= 0 && stack.data[stack.top] == target[target_index]) {
        stack.top--;
        target_index++;
    }
}

// Success if all target elements were matched
return (target_index == length);

}

int main() { int max_capacity, sequence_length, test_cases; scanf("%d %d %d", &max_capacity, &sequence_length, &test_cases);

int target_sequence[sequence_length];

for (int i = 0; i < test_cases; i++) {
    for (int j = 0; j < sequence_length; j++) {
        scanf("%d", &target_sequence[j]);
    }

    if (is_valid_pop_sequence(target_sequence, max_capacity, sequence_length)) {
        printf("YES\n");
    } else {
        printf("NO\n");
    }
}

return 0;

}


</div>This implementation avoids dynamic memory allocation and complex pointer manipulation, making it more readable and less error-prone. The stack is represented as a fixed-size array with a top index, simplifying the logic and improving performance.

Tags: stack algorithm data-structure stack-pop-sequence c-programming

Posted on Mon, 08 Jun 2026 17:55:28 +0000 by riddlejk