Bird
0
0
DSA Cprogramming~20 mins

Peek Top Element of Stack in DSA C - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Stack Peek Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
}
A10
B20
C30
D-1
Attempts:
2 left
💡 Hint
Peek returns the element at the top index of the stack array.
Predict Output
intermediate
2: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;
}
A-1
B0
CGarbage value
DRuntime error
Attempts:
2 left
💡 Hint
Check the condition when top is -1 in peek function.
🔧 Debug
advanced
2: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];
}
AReturns wrong value when stack has one element
BReturns -1 correctly when stack is empty
CCauses segmentation fault
DCompiles but returns garbage value
Attempts:
2 left
💡 Hint
Check the condition that checks if stack is empty.
Predict Output
advanced
2: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;
}
A
25
35
B
5
35
C
15
25
D
15
35
Attempts:
2 left
💡 Hint
Peek returns the last pushed element at each call.
🧠 Conceptual
expert
2: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?
AO(n^2) - Quadratic time
BO(1) - Constant time
CO(log n) - Logarithmic time
DO(n) - Linear time
Attempts:
2 left
💡 Hint
Peek only accesses the top element without iteration.