The problem. Build a stack on top of a plain array. Support push(x), pop() (return the removed value, or -1 if the stack is empty), top() (return the top value, or -1 if empty), isEmpty() and size().
push(10) push(20) top() -> 20
pop() -> 20 pop() -> 10
pop() -> -1 (empty) isEmpty() -> trueThe whole question is which end of the array is the top. Pick the wrong end and every operation moves every element.
Free account
Sign up to read the rest of this lesson: 5 more sections, 3 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come