Understanding Stack Data Structure for Interviews

Last updated by Swaminathan Iyer on Dec 21, 2024 at 06:16 PM
| Reading Time: 3 minutes

If you are a software engineer or developer preparing for a technical interview, brushing up on data structures and algorithms should be a key part of your prep. Being well-versed with these topics is crucial for cracking tech interviews at FAANG and other top tech companies. In this article, we’ll be covering the basics of the stack data structure.

We’ll cover:

  • What is a stack?
  • Basic operations on a stack
  • How insertion and deletion work in stacks
  • Stack in Java
  • Stack in Python
  • Stack Time Complexity and Space Complexity
  • Advantages and disadvantages of stack data structure

What Is Stack?

Stack is a linear data structure with only one end to access the elements and works similar to the real-world stack. We can insert or delete elements from one end only. Stack follows the LIFO (last in first out) principle. Whenever an element is added to the stack, it is added to the top, and similarly, whenever an element is deleted, it is removed from the top.

A can of Pringles is a good example of a stack. If you want to eat a chip, you pick up the one on top.

The element at the top of the stack is called the top element. The operation of inserting an element is called push(), and that of deleting an element is called pop().

When we delete the top element of the stack, if the stack is still non-empty, then the element just below the previous top element becomes the new top element of the stack. Similarly, when we insert the new element, the new element inserted will become the top element.

For example: In the can of Pringles, when you take out the chip on top, the next chip becomes the new “top.”

Following are some applications of the stack data structure:

  • Browsers use the stack data structure to keep track of the last visited sites.
  • Undo/Redo stacks in Excel or Word.
  • Stack is also used in some scheduling algorithms.
  • Stacks are also used for evaluating expressions.

Features of a stack:

  • Stack is a dynamic data structure, that is, its size is not fixed and can be increased or decreased dynamically.
  • As it is a dynamic data structure, it does not take up a fixed amount of memory like arrays.
  • The size of a stack changes with every push() or pop() operation.

Basic Operations on a Stack

Following are the basic operations you can perform on a stack:

  • push(): Adds an element to the top of the stack.
  • pop(): Removes elements from the top of the stack.
  • isEmpty(): Returns true if the stack is empty; else, returns false.
  • isFull(): Returns true if the stack is full; else, returns false.
  • top: Used to get the value of the top-most element of the stack.

How Insertion and Deletion Work in Stacks

We need to keep track of the “top” of the stack to perform insertion or deletion. While initializing the stack, we set the value of top to -1 — we can use this to check whether the stack is empty.

  • While inserting a new element, we increment the value of top and place a new element at the position pointed by top after the increment.
  • While removing an element, we decrease top and return the element pointed by top.
  • For every push operation, we need to check whether our stack is full or not.
  • For every pop operation, we need to check whether our stack is empty or not.

Here, the array arr is used to store the stack.

Stack Data Structure in Java

We’ve used a fixed-size array here to implement the stack, which makes it non-dynamic (meaning its size is fixed).

// Stack implementation in Java

class Stack {

// array used to store the stack elements

private int arr[];

// variable top to keep the track of top element of stack

private int top;

// capacity is the max size of stack

private int capacity;

 

// Creating a stack of size n and updating the top pointer.

Stack(int n) {

arr = new int[n];

capacity = n;

top = -1;

}

// push() operation to add the new element – p to stack

public void push(int p) {

// checking whether the stack is full or not.

if (isFull()) {

System.out.println(“Overflow”);

System.exit(1);

}

// inserting element p in a stack

System.out.println(“Inserting ” + p);

// incrementing the top pointer

top++;

// updating the value at new top pointer

arr[top] = p;

}

// pop() operation to remove the element from stack and return the removed element.

public int pop() {

// check if stack is empty or not

if (isEmpty()) {

System.out.println(“Stack is Empty”);

System.exit(1);

}

System.out.println(“Removing ” + arr[top]);

// decrementing the top pointer

top–;

// return the popped element.

return arr[top+1];

}

// function used to return the size of stack

public int size() {

return top + 1;

}

// function used to check whether the stack is empty or not.

public Boolean isEmpty() {

return top == -1;

}

// function used to check if the stack is full or not.

public Boolean isFull() {

return top == capacity – 1;

}

// function used to print the whole stack (from top to bottom).

public void printStack() {

System.out.println(“nFinal Stack:”);

for (int i = top; i >= 0; i–) {

System.out.println(arr[i]);

}

}

public static void main(String[] args) {

// creating new stack of size 4

Stack stack = new Stack(4);

// pushing elements in stack

stack.push(1);

stack.push(2);

stack.push(3);

stack.push(4);

// popping element.

stack.pop();

// printing the final stack.

stack.printStack();

}

}

Stack Data Structure in Python

We’ve used Python’s list to create the stack, which is a dynamic array in Python.

# Stack implementation in python

# Function used to create an empty stack

def CreateStack():

stack = []

return stack

# Function used to check whether the stack is empty or not.

def isEmpty(stack):

return len(stack) == 0

# Function used to push an element into a stack.

def Push(stack, item):

stack.append(item)

print(“Inserting: ” + item)

# Function used to pop element from the stack

def pop(stack):

# Check is the stack is empty or not

if (isEmpty(stack)):

return “Stack is Empty”

return stack.pop()

# Array used to store the stack elements

stack = CreateStack()

# pushing elements in the stack

Push(stack, str(1))

Push(stack, str(2))

Push(stack, str(3))

Push(stack, str(4))

# popping element from the stack

print(“popped item: ” + pop(stack))

# printing the whole stack

print(“stack after popping an element: ” + str(stack))

Stack Time Complexity and Space Complexity

The push() and pop() operations take constant time. Also, isEmpty() and CreateStack() have constant time complexity.

Space complexity is linear corresponding to the size of the stack because we are storing the number of elements equal to the size of the stack.

Advantages and Disadvantages of Stack Data Structures

Advantages:

  • In stacks, memory can be dynamically allocated, that is, we can allocate memory to a particular object on runtime.
  • It follows the last-in-first-out (LIFO) order; we can add and remove elements from the top of the stack, unlike arrays.

Disadvantages:

  • It lacks scalability.
  • Random access is not possible.

FAANG Interview Questions on Stack Data Structure

Following are some of the commonly asked questions on stack:

  1. Implement a stack using the queue data structure
  2. Implement a queue using the stack data structure
  3. Reverse a string using a stack data structure
  4. Find duplicate parenthesis in an expression
  5. Check if an expression is balanced or not
  6. Reverse a stack using recursion
  7. Find the previous smaller element for each array element

FAQs on Stack Data Structures

Question 1: Why do we need a stack?

Answer: Stack is used for implementing functions, evaluating expressions, and backtracking algorithms. Because of its last-in-first-out (LIFO) property, it has many advantages over other data structures, such as it can be used in cases where we only need to access or remove elements from one end.

Question 2: Can stack can be implemented using linked lists?

Answer: Yes. A stack can be implemented using linked lists. We can use a list instead of a dynamic array. The head of the linked list will be the top element of the stack. We can dynamically push elements in it and also pop elements from it using delete a node and insert new node operations in linked lists.

Looking for a Tech Interview Prep Coach?

Interview Kickstart offers the best technical interview prep courses that make you a better engineer and help you nail tech interviews.

As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

For more information on what it takes to prepare for and succeed at FAANG tech interviews, sign up for our free webinar.

————

Article contributed by Omkar Deshmukh

Last updated on: December 21, 2024
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

IK courses Recommended

Master AI tools and techniques customized to your job roles that you can immediately start using for professional excellence.

Fast filling course!

Master ML, Deep Learning, and AI Agents with hands-on projects, live mentorship—plus FAANG+ interview prep.

Master Agentic AI, LangChain, RAG, and ML with FAANG+ mentorship, real-world projects, and interview preparation.

Learn to scale with LLMs and Generative AI that drive the most advanced applications and features.

Learn the latest in AI tech, integrations, and tools—applied GenAI skills that Tech Product Managers need to stay relevant.

Dive deep into cutting-edge NLP techniques and technologies and get hands-on experience on end-to-end projects.

Select a course based on your goals

Agentic AI

Learn to build AI agents to automate your repetitive workflows

Switch to AI/ML

Upskill yourself with AI and Machine learning skills

Interview Prep

Prepare for the toughest interviews with FAANG+ mentorship

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary