Stack Interview Questions

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, meaning that the last element inserted into the stack is the first one to be removed. Stacks are essential in solving problems related to recursion, expression evaluation, and backtracking.
Share on :

Stacks are one of the most commonly used data structures in programming. A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, meaning that the last element inserted into the stack is the first one to be removed. Stacks are essential in solving problems related to recursion, expression evaluation, and backtracking.

In this blog, we will cover the top stack interview questions, complete with Python solutions to help you prepare for technical interviews.

1. Implement Stack Using an Array

Problem Statement: Write a class to implement a stack using an array (list). The class should have methods to push an element, pop an element, check if the stack is empty, and return the top element of the stack.

  • Concept: Basic Stack Operations
  • Difficulty Level: Easy

Approach: Use a Python list to store stack elements. The push operation appends an element, and the pop operation removes the last element from the list.

class Stack:
    def __init__(self):
        self.stack = []

    def is_empty(self):
        return len(self.stack) == 0

    def push(self, element):
        self.stack.append(element)

    def pop(self):
        if not self.is_empty():
            return self.stack.pop()
        return None

    def peek(self):
        if not self.is_empty():
            return self.stack[-1]
        return None

Example:

s = Stack()
s.push(10)
s.push(20)
print(s.pop())  # Output: 20
print(s.peek())  # Output: 10

2. Valid Parentheses

Problem Statement: Given a string containing just the characters (, ), {, }, [, and ], determine if the input string is valid. An input string is valid if:

  1. Open brackets are closed by the same type of brackets.
  2. Open brackets are closed in the correct order.
  • Concept: Stack for Matching Parentheses
  • Difficulty Level: Easy

Approach: Use a stack to store the open parentheses. When a closing parenthesis is encountered, check if the top of the stack contains the corresponding open parenthesis.

def is_valid_parentheses(s):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}
    
    for char in s:
        if char in mapping:
            top_element = stack.pop() if stack else '#'
            if mapping[char] != top_element:
                return False
        else:
            stack.append(char)
    
    return not stack

Example:

s = "({[]})"
print(is_valid_parentheses(s))  # Output: True

3. Min Stack

Problem Statement: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • Concept: Maintaining an additional stack for the minimum element
  • Difficulty Level: Medium

Approach: Use two stacks—one to store the elements and another to store the minimum element at each level of the stack.

class MinStack:
    def __init__(self):
        self.stack = []
        self.min_stack = []

    def push(self, val):
        self.stack.append(val)
        if not self.min_stack or val <= self.min_stack[-1]:
            self.min_stack.append(val)

    def pop(self):
        if self.stack:
            if self.stack[-1] == self.min_stack[-1]:
                self.min_stack.pop()
            return self.stack.pop()

    def top(self):
        if self.stack:
            return self.stack[-1]
        return None

    def get_min(self):
        if self.min_stack:
            return self.min_stack[-1]
        return None

Example:

min_stack = MinStack()
min_stack.push(-2)
min_stack.push(0)
min_stack.push(-3)
print(min_stack.get_min())  # Output: -3
min_stack.pop()
print(min_stack.get_min())  # Output: -2

4. Evaluate Reverse Polish Notation

Problem Statement: Evaluate the value of an arithmetic expression in Reverse Polish Notation (RPN). The valid operators are +, -, *, and /. Each operand may be an integer or another expression.

  • Concept: Stack for Expression Evaluation
  • Difficulty Level: Medium

Approach: Use a stack to store operands. When an operator is encountered, pop two elements from the stack, apply the operation, and push the result back onto the stack.

def eval_rpn(tokens):
    stack = []
    for token in tokens:
        if token not in "+-*/":
            stack.append(int(token))
        else:
            b = stack.pop()
            a = stack.pop()
            if token == '+':
                stack.append(a + b)
            elif token == '-':
                stack.append(a - b)
            elif token == '*':
                stack.append(a * b)
            elif token == '/':
                stack.append(int(a / b))  # Integer division
    return stack.pop()

Example:

tokens = ["2", "1", "+", "3", "*"]
print(eval_rpn(tokens))  # Output: 9

5. Next Greater Element

Problem Statement: You are given an array. For each element in the array, find the next greater element. If no such element exists, return -1.

  • Concept: Stack for Monotonic Decreasing Stack
  • Difficulty Level: Medium

Approach: Traverse the array in reverse and use a stack to track elements. For each element, pop the stack until you find a greater element.

def next_greater_element(arr):
    stack = []
    result = [-1] * len(arr)

    for i in range(len(arr) - 1, -1, -1):
        while stack and stack[-1] <= arr[i]:
            stack.pop()
        if stack:
            result[i] = stack[-1]
        stack.append(arr[i])
    
    return result

Example:

arr = [4, 5, 2, 25]
print(next_greater_element(arr))  # Output: [5, 25, 25, -1]

6. Implement Queue Using Stacks

Problem Statement: Implement a queue using two stacks. The queue should support enqueue (push) and dequeue (pop) operations in an efficient manner.

  • Concept: Two Stacks to Implement Queue
  • Difficulty Level: Medium

Approach: Use two stacks—one for pushing elements and one for popping elements. When dequeuing, transfer elements from the push stack to the pop stack if the pop stack is empty.

class QueueUsingStacks:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def enqueue(self, x):
        self.stack1.append(x)

    def dequeue(self):
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop() if self.stack2 else None

    def peek(self):
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1] if self.stack2 else None

    def is_empty(self):
        return not self.stack1 and not self.stack2

Example:

q = QueueUsingStacks()
q.enqueue(1)
q.enqueue(2)
print(q.dequeue())  # Output: 1
print(q.peek())     # Output: 2

7. Daily Temperatures

Problem Statement: Given a list of daily temperatures, return a list such that, for each day, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

  • Concept: Stack for Monotonic Decreasing Sequence
  • Difficulty Level: Medium

Approach: Use a stack to store indices of the temperatures. Traverse the list, and for each temperature, check if it's greater than the temperature at the top of the stack.

def daily_temperatures(T):
    stack = []
    result = [0] * len(T)

    for i in range(len(T)):
        while stack and T[i] > T[stack[-1]]:
            index = stack.pop()
            result[index] = i - index
        stack.append(i)

    return result

Example:

T = [73, 74, 75, 71, 69, 72, 76, 73]
print(daily_temperatures(T))  # Output: [1, 1, 4, 2, 1, 1, 0, 0]

8. Largest Rectangle in Histogram

Problem Statement: Given a list representing the heights of bars in a histogram, find the area of the largest rectangle that can be formed within the bounds of the histogram.

  • Concept: Stack for Histogram Problem
  • Difficulty Level: Hard

Approach: Use a stack to store the indices of the histogram bars. Traverse the list and calculate the area for each bar using the height as the smallest bar.

def largest_rectangle_area(heights

):
    stack = []
    max_area = 0
    heights.append(0)  # Append a sentinel value

    for i in range(len(heights)):
        while stack and heights[i] < heights[stack[-1]]:
            height = heights[stack.pop()]
            width = i if not stack else i - stack[-1] - 1
            max_area = max(max_area, height * width)
        stack.append(i)

    heights.pop()  # Remove the sentinel value
    return max_area

Example:

heights = [2, 1, 5, 6, 2, 3]
print(largest_rectangle_area(heights))  # Output: 10

9. Simplify Path

Problem Statement: Given an absolute path for a file (Unix-style), simplify the path by resolving .., ., and multiple slashes.

  • Concept: Stack for Path Simplification
  • Difficulty Level: Medium

Approach: Use a stack to process each component of the path. Push valid directories to the stack and pop when encountering ...

def simplify_path(path):
    stack = []
    parts = path.split("/")

    for part in parts:
        if part == "..":
            if stack:
                stack.pop()
        elif part and part != ".":
            stack.append(part)

    return "/" + "/".join(stack)

Example:

path = "/home//foo/"
print(simplify_path(path))  # Output: "/home/foo"

10. Decode String

Problem Statement: Given an encoded string, return its decoded version. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times.

  • Concept: Stack for Decoding Nested Strings
  • Difficulty Level: Medium

Approach: Use two stacks—one for storing counts and one for storing characters. For each [, push the count onto the count stack, and for each ], pop the stack and repeat the string.

def decode_string(s):
    count_stack = []
    string_stack = []
    current_string = ""
    current_num = 0

    for char in s:
        if char.isdigit():
            current_num = current_num * 10 + int(char)
        elif char == "[":
            count_stack.append(current_num)
            string_stack.append(current_string)
            current_string = ""
            current_num = 0
        elif char == "]":
            repeat_count = count_stack.pop()
            current_string = string_stack.pop() + current_string * repeat_count
        else:
            current_string += char

    return current_string

Example:

s = "3[a]2[bc]"
print(decode_string(s))  # Output: "aaabcbc"

Conclusion

Stacks are a crucial data structure in many programming problems, especially those that involve recursion, backtracking, and expression evaluation. These top stack interview questions cover fundamental stack operations, problem-solving using stacks, and more advanced concepts like decoding strings and histogram problems. By mastering these problems, you’ll be well-prepared to handle stack-based questions in coding interviews.

FAQs

1. Why are stacks important in programming? Stacks are useful in scenarios where data needs to be processed in a Last In, First Out (LIFO) order. They are frequently used in recursive algorithms, expression evaluation, and backtracking problems.

2. How do I know when to use a stack in problem-solving? You should use a stack when you need to keep track of elements in a LIFO order or when you encounter problems like matching parentheses, reversing elements, or evaluating expressions.

3. What are some real-world applications of stacks? Stacks are used in undo/redo functionality in software, call stack in programming languages, expression evaluation, and backtracking algorithms such as solving mazes or generating permutations.

4. How do I optimize stack-based algorithms? Optimizing stack-based algorithms often involves reducing unnecessary stack operations or using two stacks to improve time complexity, as seen in problems like Min Stack or Queue Using Stacks.

5. What are the time complexities for stack operations? The time complexity for basic stack operations like push, pop, peek, and is_empty is O(1), making stacks very efficient for many use cases.