Challenge - 5 Problems
Stack Peek Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of peeking the top element in this stack?
Consider the following JavaScript code that implements a stack and peeks the top element. What will be printed?
DSA Javascript
class Stack { constructor() { this.items = []; } push(element) { this.items.push(element); } peek() { return this.items[this.items.length - 1]; } } const stack = new Stack(); stack.push(10); stack.push(20); stack.push(30); console.log(stack.peek());
Attempts:
2 left
💡 Hint
Remember, peek returns the last pushed element without removing it.
✗ Incorrect
The stack has elements [10, 20, 30]. The top element is the last pushed, which is 30.
❓ Predict Output
intermediateWhat happens when peeking an empty stack?
Given the stack implementation below, what will be the output of peeking when the stack is empty?
DSA Javascript
class Stack { constructor() { this.items = []; } peek() { return this.items[this.items.length - 1]; } } const stack = new Stack(); console.log(stack.peek());
Attempts:
2 left
💡 Hint
Accessing an array element at negative index returns what?
✗ Incorrect
When the stack is empty, this.items.length is 0, so this.items[-1] is undefined in JavaScript.
❓ Predict Output
advancedWhat is the output after multiple peek calls?
Look at the code below. What will be printed after the two peek calls?
DSA Javascript
class Stack { constructor() { this.items = []; } push(element) { this.items.push(element); } peek() { return this.items[this.items.length - 1]; } pop() { return this.items.pop(); } } const stack = new Stack(); stack.push(5); stack.push(15); console.log(stack.peek()); stack.pop(); console.log(stack.peek());
Attempts:
2 left
💡 Hint
Peek shows the top element without removing it; pop removes the top element.
✗ Incorrect
First peek shows 15 (top element). After pop removes 15, peek shows 5 (new top).
❓ Predict Output
advancedWhat error occurs when peeking from a stack with no items and accessing length incorrectly?
What error will this code produce?
DSA Javascript
class Stack { constructor() { this.items = null; } peek() { return this.items[this.items.length - 1]; } } const stack = new Stack(); console.log(stack.peek());
Attempts:
2 left
💡 Hint
Check what happens when you try to access a property of null.
✗ Incorrect
this.items is null, so accessing this.items.length throws a TypeError.
🧠 Conceptual
expertWhy is peek operation in a stack O(1) time complexity?
Choose the best explanation for why the peek operation on a stack runs in constant time.
Attempts:
2 left
💡 Hint
Think about how arrays allow direct access by index.
✗ Incorrect
Peek returns the last element by index, which is a direct access operation and does not depend on stack size.
