Data Structures · Visualization

Stack: Search

Stack

Searching a stack checks whether a value exists somewhere in it, usually by conceptually popping items one at a time (or scanning from the top) until a match is found or the stack is exhausted. Time: O(n). Space: O(1).

Big-O: push / pop / peek are all O(1).

Stack: Search

Stack

Searching a stack checks whether a value exists somewhere in it, usually by conceptually popping items one at a time (or scanning from the top) until a match is found or the stack is exhausted. A pure stack does not support jumping to the middle, so this still takes a full scan in the worst case.

How Search Works

  1. Start scanning from the top of the stack.
  2. Compare each item with the target value as you go down.
  3. If a match is found, report its position (often counted as distance from the top).
  4. If the bottom is reached with no match, the value is not present.

Search Worked Example

Input: Search for 5 in stack [3, 5, 7] (7 is the top)

  1. Check 7 (top): no match
  2. Check 5: match found, 2 positions from top

Output: Found, 2 from the top

Try your own input
Stack: SearchO(n)
Scans down from the top until it finds the value or reaches the bottom.
bottom
3
5
7
← top
Active / highlighted Min stack Result
Stack: Search
Press ▶ Run to watch it step by step.
Python · Stacks & Queues in Code
def search(stack, target):
    for i, v in enumerate(reversed(stack)):
        if v == target:
            return i   # distance from top
    return -1
# example: search on [3, 5, 7]
Input: Search for 5 in stack [3, 5, 7] (7 is the top)

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Search Time & Space Complexity

TimeO(n)
SpaceO(1)

When to Use Search

  • Debugging: checking whether a specific call frame exists in the call stack
  • Checking history for a previously visited state
  • Validating whether an item was already processed via a stack-based algorithm

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.