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
StackSearching 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
- Start scanning from the top of the stack.
- Compare each item with the target value as you go down.
- If a match is found, report its position (often counted as distance from the top).
- 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)
- Check 7 (top): no match
- Check 5: match found, 2 positions from top
Output: Found, 2 from the top
Press ▶ Run to watch it step by step.
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]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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.