</>
Skip to content
DSA lessons (12/55)

DSA — Stacks

What is a Stack?

A Last-In-First-Out (LIFO) data structure.

class Stack:
    def __init__(self):
        self.items = []
    
    def push(self, item):
        self.items.append(item)
    
    def pop(self):
        if not self.is_empty():
            return self.items.pop()
    
    def peek(self):
        if not self.is_empty():
            return self.items[-1]
    
    def is_empty(self):
        return len(self.items) == 0
    
    def size(self):
        return len(self.items)

Operations

OperationTime Complexity
pushO(1)
popO(1)
peekO(1)
is_emptyO(1)

Usage Examples

# Balanced parentheses
def is_balanced(expression):
    stack = Stack()
    for char in expression:
        if char in '({[':
            stack.push(char)
        elif char in ')}]':
            if stack.is_empty():
                return False
            top = stack.pop()
            if (char == ')' and top != '(') or \
               (char == '}' and top != '{') or \
               (char == ']' and top != '['):
                return False
    return stack.is_empty()

Mini Practice

  1. Implement a stack
  2. Check balanced parentheses
  3. Implement undo functionality
  4. Convert infix to postfix

Up Next

Continue with Queues — queue data structure.

Related Topics

Frequently Asked Questions about Stacks

What is Stacks in DSA?

Stacks is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Stacks?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Stacks.

Why is Stacks important in DSA?

Stacks is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.