Web Analytics

🎯 Stack Applications

Intermediate ~25 min read ⭐⭐⭐ Interview Favorites

Now that you know stack basics, let's see where they really shine! Stack applications are everywhere: checking balanced parentheses, evaluating expressions, function calls, undo/redo. These are THE most common stack interview questions at Google, Amazon, and Microsoft!

🎯 Interview Alert - Top 5 Applications!

Master these for interviews:

  • Balanced Parentheses - #1 most common! (Easy)
  • Expression Evaluation - Postfix, infix (Medium)
  • Function Call Stack - Explain recursion (Conceptual)
  • Undo/Redo - Two-stack pattern (Design)
  • Next Greater Element - Monotonic stack (Advanced)

These appear in 80% of stack interviews!

Application 1: Balanced Parentheses

THE Most Common Stack Question!

Problem: Check if brackets are balanced

"()" → True
"()[]{}" → True
"(]" → False
"([)]" → False
"{[()]}" → True

Algorithm:

def is_balanced(s):
    stack = []
    matching = {'(': ')', '[': ']', '{': '}'}
    
    for char in s:
        if char in matching:  # Opening bracket
            stack.append(char)
        elif char in matching.values():  # Closing
            if not stack:
                return False  # No matching opening
            if matching[stack.pop()] != char:
                return False  # Mismatch
    
    return len(stack) == 0  # All matched?

Time: O(n), Space: O(n)

Key insight: Opening → push, Closing → pop and check!

See It in Action

Watch how stacks solve real problems:

Application 2: Expression Evaluation

Three Notations

Infix (Human-readable)
A + B * C
(A + B) * C

Operator between operands - what we write

Postfix (Computer-friendly)
A B C * +
A B + C *

Operator after operands - easy to evaluate!

Prefix (Polish notation)
+ A * B C
* + A B C

Operator before operands - less common

Infix to Postfix Conversion

Why Convert?

Postfix has NO parentheses and is easy to evaluate!

def infix_to_postfix(expr):
    precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
    stack = []
    postfix = []
    
    for char in expr:
        if char.isalnum():  # Operand
            postfix.append(char)
        elif char == '(':
            stack.append(char)
        elif char == ')':
            while stack and stack[-1] != '(':
                postfix.append(stack.pop())
            stack.pop()  # Remove '('
        else:  # Operator
            while (stack and stack[-1] != '(' and
                   precedence.get(stack[-1], 0) >= precedence[char]):
                postfix.append(stack.pop())
            stack.append(char)
    
    while stack:
        postfix.append(stack.pop())
    
    return ''.join(postfix)

Example: A+B*C → ABC*+

Why? * has higher precedence, so B*C happens first!

Evaluate Postfix Expression

Simple Algorithm!

def evaluate_postfix(expr):
    stack = []
    
    for char in expr:
        if char.isdigit():
            stack.append(int(char))
        else:
            b = stack.pop()
            a = stack.pop()
            if char == '+': stack.append(a + b)
            elif char == '-': stack.append(a - b)
            elif char == '*': stack.append(a * b)
            elif char == '/': stack.append(a // b)
    
    return stack[0]

Example: 23*5+ → 2*3+5 = 11

  1. Push 2, Push 3
  2. See *, pop 3 and 2, push 2*3=6
  3. Push 5
  4. See +, pop 5 and 6, push 6+5=11

Application 3: Function Call Stack

How Recursion Works

Every function call creates a stack frame:

main() {
    processData();  // Push main's frame
}

processData() {
    validate();     // Push processData's frame
}

validate() {
    return;         // Pop validate's frame
                    // Pop processData's frame
                    // Pop main's frame
}

Stack frames contain:

  • Local variables
  • Parameters
  • Return address

Stack overflow: Too many nested calls!

Application 4: Undo/Redo

Two-Stack Pattern

class TextEditor:
    def __init__(self):
        self.text = ""
        self.undo_stack = []
        self.redo_stack = []
    
    def type(self, char):
        self.undo_stack.append(self.text)
        self.text += char
        self.redo_stack = []  # Clear redo!
    
    def undo(self):
        if self.undo_stack:
            self.redo_stack.append(self.text)
            self.text = self.undo_stack.pop()
    
    def redo(self):
        if self.redo_stack:
            self.undo_stack.append(self.text)
            self.text = self.redo_stack.pop()

Key insight: New action clears redo stack!

The Complete Code

Output
Click Run to execute your code

Common Mistakes

❌ Mistake #1: Forgetting Empty Check

# WRONG - crashes if stack empty!
top = stack.pop()

# RIGHT - check first
if stack:
    top = stack.pop()

❌ Mistake #2: Wrong Operand Order in Postfix

# WRONG - reversed!
b = stack.pop()
a = stack.pop()
result = b - a  # Wrong order!

# RIGHT - first pop is second operand
b = stack.pop()
a = stack.pop()
result = a - b  # Correct!

Interview Tips

💡 How to Ace Stack Application Questions

  • Balanced Parentheses: Most common! Practice variations
  • Expression Evaluation: Know all three notations
  • Operator Precedence: *, / before +, -
  • Postfix Evaluation: Operand order matters!
  • Two Stacks: Undo/redo pattern appears often
  • Edge Cases: Empty string, single char, all opening

Summary

Stack Applications Mastery

  1. Balanced Parentheses: Opening→push, Closing→pop & check
  2. Expression Evaluation: Postfix is easiest to evaluate
  3. Infix to Postfix: Use operator precedence
  4. Function Calls: Stack frames enable recursion
  5. Undo/Redo: Two-stack pattern

Interview tip: Balanced parentheses is THE most common stack question. Master it first, then move to expression evaluation!

What's Next?

You've mastered stack applications! Next: Advanced Stack Problems - Next Greater Element, Min Stack, and more challenging problems!

Practice: Implement balanced parentheses and postfix evaluation from scratch!