DSA — Linear DS

Stack (LIFO)

Last In, First Out. Push adds to top, pop removes from top. Think: stack of plates.

— min read
O(1)Push
O(1)Pop
O(n)Search
LIFOOrder
Call Stack
// STACK OPERATIONS
Use Push/Pop to operate
How It Works
Python Code
Complexity
Quiz
Practice
01
Push
Add element to top — O(1).
stack.append(x)
02
Pop
Remove and return top element — O(1).
stack.pop()
03
Peek
View top without removing — O(1).
stack[-1]
04
Uses
Call stack, undo/redo, balanced parentheses, DFS.
Python — Stack & Balanced Parens
# Python list as stack
stack = []
stack.append(10)     # push — O(1)
stack.append(20)
stack.append(30)
top = stack[-1]      # peek — O(1) → 30
val = stack.pop()    # pop  — O(1) → 30

# Balanced parentheses
def is_valid(s):
    st = []
    for c in s:
        if c == '(': st.append(c)
        elif st: st.pop()
        else: return False
    return not st
O(1)
Push
Append to end of list
O(1)
Pop
Remove from end of list
O(1)
Peek
Read last element
DFS
Graph Use
Stack implements iterative DFS
What order does a stack return elements?
Progress0 / 9 solved
9 problems · 5 PBC · 4 Startup
#061 Next Greater Element Amazon, Google PBC
#062 Valid Parentheses Meta, Microsoft PBC
#063 Evaluate Reverse Polish Notation Google PBC
#064 Implement Queue using Stacks Amazon PBC
#065 The Celebrity Problem Microsoft, Google PBC
#066 Stock Span Problem Meesho, Ola STARTUP
#068 Implement Stack using Queues Cure.fit STARTUP
#069 First Non-Repeating Char in Stream Zepto STARTUP
#070 LRU Cache Design Cogoport STARTUP