Stack

Implementation Using Array

What is Stack Implementation Using Array?

A stack is a linear data structure that follows the LIFO (Last In First Out) principle. Arrays provide a simple way to implement stack operations with constant time complexity.

Algorithmic Steps

Stack Basic Operations

Step 1

Initialize Stack

  1. Create an empty array to store elements
  2. Initialize top pointer/index to -1
  3. Optional: Set maximum size limit
Step 2

push()

  1. Check if stack is full
  2. If full, return "Stack Overflow"
  3. Increment top pointer
  4. Store element at array[top]
Step 3

pop()

  1. Check if stack is empty
  2. If empty, return "Stack Underflow"
  3. Access element at array[top]
  4. Decrement top pointer
  5. Return the element

Stack Helper Operations

Step 1

peek()

  1. Check if stack is empty
  2. If empty, return null
  3. Return array[top] without removal
Step 2

isEmpty()

  1. Return true if top pointer is -1
  2. Return false otherwise
Step 3

isFull()

  1. Return true if top equals (max_size - 1)
  2. Return false otherwise

Time Complexity

OperationComplexity
push()O(1)
pop()O(1)
peek()O(1)
isEmpty()O(1)

Key Characteristics

  • LIFO Principle: Last element added is first removed
  • Dynamic Size: Can grow until memory limits
  • Efficiency: All operations work in constant time
  • Versatility: Foundation for many algorithms
Daily DSA Challenge by Hello World

Stack Implementation using Array

// Stack Implementation using Array (JavaScript)
class Stack {
  constructor(size = 10) {
    this.items = new Array(size);
    this.top = -1;
    this.capacity = size;
  }

  // Push operation
  push(element) {
    if (this.isFull()) {
      console.log("Stack Overflow");
      return;
    }
    this.items[++this.top] = element;
  }

  // Pop operation
  pop() {
    if (this.isEmpty()) {
      console.log("Stack Underflow");
      return undefined;
    }
    return this.items[this.top--];
  }

  // Peek operation
  peek() {
    if (this.isEmpty()) {
      console.log("Stack is empty");
      return undefined;
    }
    return this.items[this.top];
  }

  // Check if stack is empty
  isEmpty() {
    return this.top === -1;
  }

  // Check if stack is full
  isFull() {
    return this.top === this.capacity - 1;
  }

  // Get stack size
  size() {
    return this.top + 1;
  }

  // Print stack contents
  print() {
    if (this.isEmpty()) {
      console.log("Stack is empty");
      return;
    }
    console.log("Stack contents:");
    for (let i = this.top; i >= 0; i--) {
      console.log(this.items[i]);
    }
  }
}

// Usage
const stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.push(30);
console.log("Top element:", stack.peek()); // 30
console.log("Stack size:", stack.size());  // 3
stack.print();
stack.pop();
console.log("After pop, top element:", stack.peek()); // 20

Done With the Learning

Mark Stack using Array as done and view it on your dashboard

Explore other implementation