700208. Implement stack using array

Basic

Implement Stack using Array

Summary

Implement a stack using an array. A stack is a linear data structure that follows the LIFO (Last In First Out) principle, meaning the last element added to the stack will be the first one to be removed. The key concepts involved in this problem are arrays and stacks.

Detailed Explanation

To implement a stack using an array, we can create an array of a fixed size and use two pointers: top and size. The top pointer points to the top element of the stack, and the size pointer keeps track of the number of elements in the stack. When an element is pushed onto the stack, it's stored at the index pointed by top, which is then incremented. When an element is popped from the stack, the value at the index pointed by top is returned, and top is decremented.

Here's a step-by-step breakdown of the solution:

  1. Initialize an array with a fixed size.
  2. Set top to -1 (since arrays are 0-indexed) and size to 0.
  3. When an element is pushed onto the stack:
    • Store the element at the index pointed by top.
    • Increment top.
    • Increment size.
  4. When an element is popped from the stack:
    • Return the value at the index pointed by top.
    • Decrement top.
    • Decrement size if necessary (if the stack becomes empty).
  5. Repeat steps 3 and 4 until the stack is empty or we want to check if the stack is full.

Optimized Solutions

Java

View on GeeksforGeeks
class Stack {
    private int[] array;
    private int top;
    private int size;

    public Stack(int capacity) {
        array = new int[capacity];
        top = -1;
        size = 0;
    }

    public void push(int value) {
        if (size == array.length) {
            // Handle stack overflow
        }
        array[++top] = value;
        size++;
    }

    public int pop() {
        if (size == 0) {
            // Handle empty stack
        }
        return array[top--];
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.