Skip to content

visual walkthrough

Backspace String Compare

EasyStack SimulationReported at: GoogleAppleIBM+3

Stack simulation, with a two-pointer O(1)-space follow-up.

Solve on LeetCode

The idea

Typing the text into a stack mirrors what a keyboard does: letters pile up and '#' removes the top one. Comparing the two final stacks answers the question.

Going backwards lets you skip erased letters without a stack: a '#' tells you how many letters to ignore before the next real one.

Complexity

approachtimespace
Type into a stackO(n)O(n)
Two pointers from the backO(n)O(1)

More walkthroughs