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 x) {
stack.push_back([1]);
if (minStack.empty() || x <= minStack.back()) {
minStack.push_back(x);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using minStack.back() instead of x causes wrong values in the main stack.
Using stack.back() causes pushing the last element again, not the new one.
✗ Incorrect
We push the element x onto the main stack. The code pushes x to stack, so the blank must be 'x'.
2fill in blank
mediumComplete the code to pop the top element from the stack and update minStack accordingly.
DSA C++
void pop() {
if (stack.back() == [1]) {
minStack.pop_back();
}
stack.pop_back();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using minStack.back() in the comparison causes incorrect behavior.
Using stack.front() or minStack.front() is wrong because we need the top element.
✗ Incorrect
We compare the top of the main stack with the top of minStack. If equal, pop from minStack. So the blank is stack.back().
3fill in blank
hardFix the error in the getMin function to return the current minimum element.
DSA C++
int getMin() {
return [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning stack.back() returns the last pushed element, not the minimum.
Using front() returns the bottom element, not the top.
✗ Incorrect
The current minimum is at the top of minStack, so we return minStack.back().
4fill in blank
hardFill both blanks to correctly initialize the MinStack constructor.
DSA C++
MinStack() {
stack = std::vector<int>[1];
minStack = std::vector<int>[2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using () is invalid syntax for vector initialization here.
Initializing with {0} or {-1} adds unwanted elements.
✗ Incorrect
We initialize both vectors as empty using {}.
5fill in blank
hardFill all three blanks to complete the MinStack class definition with push, pop, and getMin methods.
DSA C++
class MinStack { private: std::vector<int> stack; std::vector<int> minStack; public: void push(int x) { stack.push_back([1]); if (minStack.empty() || x <= minStack.back()) { minStack.push_back(x); } } void pop() { if (stack.back() == [2]) { minStack.pop_back(); } stack.pop_back(); } int getMin() { return [3]; } };
Attempts:
3 left
💡 Hint
Common Mistakes
Using minStack.back() in push instead of x.
Comparing minStack.back() in pop instead of stack.back().
Returning stack.back() in getMin instead of minStack.back().
✗ Incorrect
push uses x, pop compares stack.back(), getMin returns minStack.back().
