Challenge - 5 Problems
Stack Peek Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of peeking the top element in this stack?
Consider a stack implemented using an array with the following operations. What will be printed after peeking the top element?
DSA C
#include <stdio.h> #define MAX 5 int stack[MAX]; int top = -1; void push(int x) { if (top < MAX - 1) { stack[++top] = x; } } int peek() { if (top == -1) return -1; return stack[top]; } int main() { push(10); push(20); push(30); printf("%d\n", peek()); return 0; }
Attempts:
2 left
💡 Hint
Peek returns the element at the top index of the stack array.
✗ Incorrect
The stack has elements pushed in order: 10, 20, 30. The top points to the last pushed element, which is 30. So peek returns 30.
❓ Predict Output
intermediate2:00remaining
What happens when peeking an empty stack?
Given the stack implementation below, what will be the output when peek is called on an empty stack?
DSA C
#include <stdio.h> #define MAX 3 int stack[MAX]; int top = -1; int peek() { if (top == -1) return -1; return stack[top]; } int main() { printf("%d\n", peek()); return 0; }
Attempts:
2 left
💡 Hint
Check the condition when top is -1 in peek function.
✗ Incorrect
When the stack is empty, top is -1. The peek function returns -1 in this case, indicating no elements.
🔧 Debug
advanced2:00remaining
Identify the error in this peek function implementation
The peek function below is intended to return the top element of the stack. What error will occur when this code runs?
DSA C
int peek() { if (top == 0) return -1; return stack[top]; }
Attempts:
2 left
💡 Hint
Check the condition that checks if stack is empty.
✗ Incorrect
The condition 'top == 0' incorrectly treats stack with one element as empty. The empty stack condition is 'top == -1'. So peek returns -1 even when one element exists.
❓ Predict Output
advanced2:00remaining
What is the output after multiple push and peek operations?
Given the following code, what will be printed?
DSA C
#include <stdio.h> #define MAX 4 int stack[MAX]; int top = -1; void push(int x) { if (top < MAX - 1) { stack[++top] = x; } } int peek() { if (top == -1) return -1; return stack[top]; } int main() { push(5); push(15); printf("%d\n", peek()); push(25); push(35); printf("%d\n", peek()); return 0; }
Attempts:
2 left
💡 Hint
Peek returns the last pushed element at each call.
✗ Incorrect
After pushing 5 and 15, peek returns 15. After pushing 25 and 35, peek returns 35.
🧠 Conceptual
expert2:00remaining
What is the time complexity of the peek operation in a stack?
Consider a stack implemented using an array or linked list. What is the time complexity of the peek operation?
Attempts:
2 left
💡 Hint
Peek only accesses the top element without iteration.
✗ Incorrect
Peek returns the top element directly using the top index or pointer, so it runs in constant time O(1).
