Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an element onto the stack.
DSA Java
public void push(int value) {
if (size == capacity) {
resize();
}
arr[size] = [1];
size++;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using size instead of value to assign array element.
Assigning to arr instead of arr[size].
✗ Incorrect
We assign the input value to the array at the current size index before increasing size.
2fill in blank
mediumComplete the code to resize the array when capacity is reached.
DSA Java
private void resize() {
capacity = capacity [1] 2;
int[] newArr = new int[capacity];
for (int i = 0; i < size; i++) {
newArr[i] = arr[i];
}
arr = newArr;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Dividing capacity instead of multiplying.
✗ Incorrect
We multiply capacity by 2 to double the array size.
3fill in blank
hardFix the error in the pop method to correctly return the top element.
DSA Java
public int pop() {
if (size == 0) {
throw new EmptyStackException();
}
size--;
return arr[[1]];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using size - 1 after decrementing size.
Using capacity - 1 or 0 as index.
✗ Incorrect
After decreasing size, the top element is at index size.
4fill in blank
hardFill both blanks to check if the stack is empty and return the correct boolean.
DSA Java
public boolean isEmpty() {
return size [1] [2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' operator.
Comparing size to size instead of 0.
✗ Incorrect
The stack is empty if size equals 0.
5fill in blank
hardFill in the blank to implement the peek method that returns the top element without removing it.
DSA Java
public int peek() {
if (size == 0) {
throw new EmptyStackException();
}
return arr[[1]];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using size as index which is out of bounds.
Using capacity or 0 as index.
✗ Incorrect
The top element is at index size - 1 without changing size.
