AlgoDaily

Stacks and Queues

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Controlled Access

From sequences to rules

In Arrays and Strings, you learned to work with ordered data by scanning, indexing, slicing, and updating.

In Sorting and Searching, you saw that choosing the right structure can create shortcuts.

Now we add two simple structures that show up constantly in interviews:

  • Stack: last item in, first item out
  • Queue: first item in, first item out

The key idea is not that they store data differently from lists. The key idea is that they restrict how you access the data.

That restriction is what makes many interview problems easier to reason about.

Controlled Access

Two Access Rules

Same storage, different promise

A stack and a queue both hold multiple values, but each gives you a different promise about which value comes out next.

Stack: LIFO

Last In, First Out

push A     push B     pop -> B

bottom [ A, B ] top

Think of a stack of plates. The last plate placed on top is the first plate removed.

Queue: FIFO

First In, First Out

enqueue A   enqueue B   dequeue -> A

front [ A, B ] back

Think of a line at a trading desk coffee machine: whoever arrived first gets served first.

In interviews, your job is often to notice: Do I need the newest unfinished thing, or the oldest waiting thing?

Two Access Rules

Stack In Python

Use a list as a stack

In Python, the most common stack implementation is just a list.

Use:

  • append(x) to push onto the top
  • pop() to remove from the top

Both operations are efficient at the end of a list.

Here is a tiny stack example that tracks recent actions:

```python
stack = []

stack.append("open order form")
stack.append("type quantity")
stack.append("submit order")

print("Current stack:", stack)

last_action = stack.pop()
print("Undo:", last_action)
print("After undo:", stack)

stack.append("edit quantity")
print("After new action:", stack)
```

Which Structure?

You are solving an interview problem where you repeatedly need to process the most recent unfinished item first.

Which structure best matches that access pattern?

Queue In Python

Use deque as a queue

For queues, use collections.deque.

Why not just use a list?

  • list.append(x) at the end is fine
  • but list.pop(0) must shift the remaining elements left
  • that makes repeated front removals inefficient

A deque supports efficient operations at both ends.

Use:

  • append(x) to enqueue at the back
  • popleft() to dequeue from the front
```python
from collections import deque

orders = deque()

orders.append("order_A")
orders.append("order_B")
orders.append("order_C")

print("Waiting orders:", list(orders))

first = orders.popleft()
print("Processing:", first)
print("Still waiting:", list(orders))

orders.append("order_D")
print("After new order:", list(orders))
```

List Queue Trap

True or false:

Using a Python list with pop(0) is usually a good queue implementation for large interview inputs.

When To Use

The interview decision

When you feel confused, ask one access question:

Which waiting item should be handled next?

Choose a stack when...

You need the newest unresolved thing.

Common signals:

  • undo behavior
  • nested structures
  • matching open/close symbols
  • backtracking-like cleanup
Choose a queue when...

You need the oldest waiting thing.

Common signals:

  • fair order of arrival
  • task scheduling
  • buffering events
  • level-by-level processing later in graph and tree problems

You do not need to memorize every pattern yet. Just connect the problem statement to the access rule.

When To Use

Push Method

Fill in the blank.

In Python, when using a list as a stack, you push an item onto the top with:

stack.____(item)

Parentheses Pattern

A classic stack interview problem

One of the most common stack uses is checking whether brackets are properly matched.

Example:

"({[]})"  -> valid
"([)]"    -> invalid

Why stack?

Because when you see a closing bracket, it must match the most recent unmatched opening bracket.

That phrase — most recent unmatched — is a stack signal.

```python
def is_valid_brackets(s):
    stack = []
    pairs = {")": "(", "]": "[", "}": "{"}

    for ch in s:
        if ch in "([{":
            stack.append(ch)
        else:
            if not stack:
                return False
            top = stack.pop()
            if top != pairs[ch]:
                return False

    return len(stack) == 0

print(is_valid_brackets("({[]})"))
print(is_valid_brackets("([)]"))
print(is_valid_brackets("((()"))
```

Interview Checklist

What to say out loud

For interview prep, do not just code the structure. Explain why it fits.

Use this template:

  1. Access rule: “I need the newest item” or “I need the oldest item.”
  2. Structure: “That suggests a stack” or “That suggests a queue.”
  3. Python tool:
    • Stack: list with append() and pop()
    • Queue: deque with append() and popleft()
  4. Complexity: Each push/pop or enqueue/dequeue is typically O(1).

Stacks and queues are small ideas, but they become building blocks for harder topics. Next, linked lists will show another way to organize access and updates.

Interview Checklist

Open interactive view →