Skip to content
UniCircle
EasyCodingClasses and arrays

Implement a fixed-capacity stack with an array

Question JAVA-COD-108

Implement a stack of integers backed by a plain array of fixed capacity C (no ArrayList or ArrayDeque). Process q commands:

  • PUSH x — push x, or print OVERFLOW if the stack is full.
  • POP — print and remove the top, or print UNDERFLOW if empty.
  • PEEK — print the top without removing it, or EMPTY.
  • SIZE — print the number of elements.

Constraints

  • 1 ≤ C ≤ 100000
  • 1 ≤ q ≤ 100000

Input and output

Input
Line 1: C and q. Next q lines: one command each.
Output
One line for every command that prints something.

Examples

Input 1

2 6
PUSH 5
PUSH 8
PUSH 1
PEEK
POP
SIZE

Output

OVERFLOW
8
8
1

The third push fails (capacity 2); the top is 8; after popping it, one element remains.

Input 2

3 2
POP
PEEK

Output

UNDERFLOW
EMPTY

The stack starts empty.

Show hints
  • Keep an int array and a top index.
  • Check the bounds before reading or writing the array.
Show the explanation

Store elements in int[] data = new int[C] and keep top, the number of elements. push writes data[top++], pop returns data[--top], and peek reads data[top − 1]; every operation is O(1). Guarding each operation (full before push, empty before pop/peek) avoids ArrayIndexOutOfBoundsException. Making data and top private and exposing only these methods is the encapsulation point interviewers look for.

Original UniCircle question. Last reviewed 22 Oct 2026.