Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the array that will store stack elements.
DSA Java
int[] stack = new int[[1]];Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names instead of a number for array size.
Leaving the array size blank.
✗ Incorrect
The stack array must be declared with a fixed size, here 10.
2fill in blank
mediumComplete the code to initialize the top pointer for the stack.
DSA Java
int top = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Initializing top to 0 which means stack has one element.
Initializing top to stack length which is out of bounds.
✗ Incorrect
The top is initialized to -1 to indicate the stack is empty.
3fill in blank
hardFix the error in the push method to correctly add an element to the stack.
DSA Java
public void push(int value) {
if(top < stack.length - 1) {
top = top [1] 1;
stack[top] = value;
} else {
System.out.println("Stack Overflow");
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using minus instead of plus causing wrong index.
Using multiplication or division which is incorrect here.
✗ Incorrect
To move top up by one, use top = top + 1.
4fill in blank
hardFill both blanks to correctly implement the pop method that removes and returns the top element.
DSA Java
public int pop() {
if(top >= 0) {
int value = stack[top];
top = top [1] 1;
return value;
} else {
System.out.println("Stack Underflow");
return [2];
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Incrementing top instead of decrementing.
Returning 0 which could be a valid stack value.
✗ Incorrect
Decrement top by 1 after popping, and return -1 if stack is empty.
5fill in blank
hardFill all three blanks to complete the peek method that returns the top element without removing it.
DSA Java
public int peek() {
if(top [1] 0) {
return stack[[2]];
} else {
System.out.println("Stack is empty");
return [3];
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of >= causing wrong empty check.
Returning 0 which may be a valid element.
✗ Incorrect
Check if top >= 0, return stack[top], else return -1 for empty stack.
