D. Using pop() removes the top element instead of just peeking
Solution
Step 1: Understand pop() behavior
pop() removes and returns the top element, modifying the stack.
Step 2: Identify peek operation requirement
Peek should return the top element without removing it, so pop() is incorrect here.
Final Answer:
Using pop() removes the top element instead of just peeking -> Option D
Quick Check:
pop() removes element, peek should not [OK]
Hint: Peek must not remove element; pop() does [OK]
Common Mistakes:
Using pop() instead of accessing last element
Returning stack[0] which is bottom element
Ignoring side effects of pop()
5. You have a stack implemented as an array stack. You want to safely peek the top element but return null if the stack is empty to avoid errors. Which TypeScript code snippet correctly does this?
hard
A. return stack.pop() || null;
B. return stack.length ? stack[stack.length - 1] : null;
C. return stack[0] || null;
D. return stack[stack.length];
Solution
Step 1: Check if stack is empty
Use stack.length to verify if stack has elements.
Step 2: Return top element or null
If stack is not empty, return stack[stack.length - 1], else return null.