← Back to Tutorials

4. Stacks & Queues (Days 45—59)

Valid Parentheses

def isValid(s: str) -> bool:
    stack = []
    pairs = {')': '(', '}': '{', ']': '['}
    for c in s:
        if c in pairs:
            if not stack or stack.pop() != pairs[c]:
                return False
        else:
            stack.append(c)
    return not stack

Queue Using Stacks

// Java — Two stacks
class MyQueue {
    Stack<Integer> in = new Stack<>();
    Stack<Integer> out = new Stack<>();

    public void push(int x) { in.push(x); }
    public int pop() {
        if (out.isEmpty()) transfer();
        return out.pop();
    }
    public int peek() {
        if (out.isEmpty()) transfer();
        return out.peek();
    }
    private void transfer() {
        while (!in.isEmpty()) out.push(in.pop());
    }
}

Next Greater Element

def nextGreaterElement(nums):
    stack, result = [], [-1] * len(nums)
    for i in range(len(nums)):
        while stack and nums[i] > nums[stack[-1]]:
            result[stack.pop()] = nums[i]
        stack.append(i)
    return result

More Problems

ProblemPatternComplexity
Backspace String CompareStack simulation, two pointersO(n), O(n)
Min StackTwo stacks (values + mins)O(1) per op
Decode StringStack for counts and stringsO(n), O(n)
Daily TemperaturesMonotonic decreasing stackO(n), O(n)
✏️ Exercise: Implement Valid Parentheses with all bracket types, then build a Min Stack class with O(1) getMin(). Solve Backspace Compare with O(n) time.