Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a stack of integers for storing indices.
DSA C++
std::stack<[1]> s;Attempts:
3 left
💡 Hint
Common Mistakes
Using float or double instead of int for indices.
Using char which is not suitable for indices.
✗ Incorrect
We use a stack of integers to store indices of stock prices.
2fill in blank
mediumComplete the condition to pop from stack while current price is greater than or equal to price at stack top.
DSA C++
while (!s.empty() && price[i] [1] price[s.top()]) { s.pop(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of >= causes wrong logic.
Using == or <= does not correctly identify smaller or equal prices.
✗ Incorrect
We pop while current price is greater than or equal to price at top index in stack.
3fill in blank
hardFix the error in calculating span when stack is empty.
DSA C++
span[i] = s.empty() ? [1] : i - s.top();Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 causes span to be zero incorrectly.
Using i alone misses the +1 count.
✗ Incorrect
If stack is empty, span is i + 1 since it includes all days from the beginning up to the current day.
4fill in blank
hardFill both blanks to push current index and iterate over all prices.
DSA C++
for (int i = 0; i [1] n; i++) { // logic s.[2](i); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes out of bounds error.
Using pop instead of push removes elements incorrectly.
✗ Incorrect
We loop from 0 to n-1 using i < n and push current index i onto stack.
5fill in blank
hardFill all three blanks to complete the stock span function.
DSA C++
std::vector<int> calculateSpan(const std::vector<int>& price, int n) {
std::stack<int> s;
std::vector<int> span(n);
span[0] = [1];
s.push(0);
for (int i = 1; i [2] n; i++) {
while (!s.empty() && price[i] [3] price[s.top()]) {
s.pop();
}
span[i] = s.empty() ? i + 1 : i - s.top();
s.push(i);
}
return span;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing span[0] to 0 causes wrong span.
Using i <= n causes index out of range.
Using < instead of >= in while condition breaks logic.
✗ Incorrect
Initialize span[0] = 1, loop i < n, and pop while price[i] >= price at stack top.
