Stack Height Tracker

Stack Data Structures Simulation

Stack Height Tracker

You are given an array of strings that represent a sequence of stack operations. Each string is in one of the following formats:

  • push x where x is an integer to be pushed onto the stack
  • pop which indicates a pop operation

Your task is to simulate these operations on an initially empty stack and determine the maximum stack size (i.e., the highest number of items in the stack) reached during the process. If at any point a pop operation is encountered when the stack is empty (i.e., an invalid operation), immediately return -1.

Input

  • An array of strings representing the operations.

Output

  • An integer representing the maximum number of elements in the stack at any point, or -1 if an invalid pop operation occurs.

Example

Given the operations:

["push 3", "push 5", "pop", "push 2", "push 1", "pop", "pop"]

The simulation proceeds as:

  1. push 3 → stack: [3] (size 1)
  2. push 5 → stack: [3, 5] (size 2) ← max so far: 2
  3. pop → stack: [3] (size 1)
  4. push 2 → stack: [3, 2] (size 2)
  5. push 1 → stack: [3, 2, 1] (size 3) ← max so far: 3
  6. pop → stack: [3, 2] (size 2)
  7. pop → stack: [3] (size 1)

The highest number of elements in the stack was 3, so the function should return 3.

Historical Note

On April 3, 1973, the first handheld cellular phone call was made. While technology has evolved significantly since then, the fundamental concept of managing resources efficiently—like managing the stack in this challenge—remains a cornerstone of computer science.

Good luck!