Peek at the Top After Each Operation
Solve this ProblemEasy10 min
Topics
BasicsStack
Companies
TCSInfosysWipro
Process
ops on an initially empty stack: a positive number means push it, and 0 means pop (ignored if the stack is empty). After every operation, record the value on top of the stack, or −1 if it is empty.
PeekPeek (Top)Looking at the item on top of a stack without removing it. reads the top item without removing it. It is how many algorithms "look before they act" — for example, checking the most recent opening bracket before deciding whether a closing bracket matches. Like pop, peek must handle the empty case.
Test Case 1:
Input:ops = [4, 9, 0, 0, 0, 6]
Output:[4, 9, 4, -1, -1, 6]
Explanation:Push 4, push 9, pop (top is 4 again), pop (empty: −1), pop on empty (still −1), push 6.
Test Case 2:
Input:ops = [0]
Output:[-1]
Explanation:Popping an empty stack changes nothing.
Constraints
- ◆
1 ≤ ops.length ≤ 1000 - ◆
0 ≤ ops[i] ≤ 1000000 (a positive value means push it, 0 means pop)
Try the Dry Run
Approach & Solutions
Array with a Top IndexGood
Keep the stack in an array with a top index. A positive op pushes it; a 0 pops, but only if the stack is not empty. After every op, peek: record stack[top], or −1 when top is −1. Peeking never changes the stack.
Time
O(n)Space
O(n)Java
class Solution {
public int[] topAfterEach(int[] ops) {
int[] stack = new int[ops.length];
int top = -1;
int[] tops = new int[ops.length];
for (int i = 0; i < ops.length; i++) {
if (ops[i] > 0) {
stack[++top] = ops[i];
} else if (top >= 0) {
top--;
}
tops[i] = top >= 0 ? stack[top] : -1;
}
return tops;
}
}Built-in Stack with PeekOptimal
Use the language's stack: ArrayDeque with push, pop and peek in Java, std::stack with top() in C++, and a list whose last element (stack[-1] / stack[stack.length - 1]) is the top in Python and JavaScript. Always check for emptiness before peeking or popping. C keeps the array version.
Time
O(n)Space
O(n)Java
class Solution {
public int[] topAfterEach(int[] ops) {
Deque<Integer> stack = new ArrayDeque<>();
int[] tops = new int[ops.length];
for (int i = 0; i < ops.length; i++) {
if (ops[i] > 0) {
stack.push(ops[i]);
} else if (!stack.isEmpty()) {
stack.pop();
}
tops[i] = stack.isEmpty() ? -1 : stack.peek();
}
return tops;
}
}