Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an element onto the stack.
DSA C++
void push(int value) {
if (size == capacity) {
resize();
}
arr[size] = [1];
size++;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'capacity' instead of 'value' to assign.
Using 'size' as the value instead of index.
Assigning to 'arr[size]' with wrong value.
✗ Incorrect
We assign the input value to the array at the current size index before increasing size.
2fill in blank
mediumComplete the code to check if the stack is empty.
DSA C++
bool isEmpty() const {
return [1] == 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking capacity instead of size.
Checking the array pointer instead of size.
✗ Incorrect
The stack is empty when size is zero.
3fill in blank
hardFix the error in the pop function to correctly remove the top element.
DSA C++
int pop() {
if (isEmpty()) {
throw std::out_of_range("Stack is empty");
}
size[1];
return arr[size];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using ++ instead of -- causing out-of-bounds access.
Using += or -= without a value.
✗ Incorrect
We decrease size by one before returning the top element.
4fill in blank
hardFill both blanks to resize the array by doubling capacity and copying elements.
DSA C++
void resize() {
capacity = capacity [1] 2;
int* newArr = new int[capacity];
for (int i = 0; i [2] size; i++) {
newArr[i] = arr[i];
}
delete[] arr;
arr = newArr;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '*' for capacity doubling.
Using '<=' in loop causing out-of-bounds.
✗ Incorrect
Capacity is doubled using '*', and loop runs while i < size to copy all elements.
5fill in blank
hardFill all three blanks to implement the peek function that returns the top element without removing it.
DSA C++
int peek() const {
if ([1]()) {
throw std::out_of_range("Stack is empty");
}
return arr[[2] - [3]];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using capacity instead of size for index.
Using size + 1 instead of size - 1.
✗ Incorrect
Check if stack is empty using isEmpty(), then return element at size - 1 index.
