Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push the current index onto the stack.
DSA C++
if (stack.empty() || heights[[1]] >= heights[stack.top()]) { stack.push(i); }
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing the height instead of the index.
Using stack.top() instead of the current index.
✗ Incorrect
We push the current index 'i' onto the stack to keep track of bars in ascending order.
2fill in blank
mediumComplete the code to calculate the width of the rectangle when popping from the stack.
DSA C++
int width = stack.empty() ? i : i - stack.top() - [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of 1, causing off-by-one error.
Using i or -1 incorrectly.
✗ Incorrect
Width is calculated as the difference between current index and the index on top of the stack minus one.
3fill in blank
hardFix the error in the condition to pop from the stack when current height is less than the height at stack top.
DSA C++
while (!stack.empty() && heights[i] [1] heights[stack.top()]) { // pop and calculate area }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' or '>=' which reverses the logic.
Using '<=' which includes equal heights incorrectly.
✗ Incorrect
We pop from the stack while the current height is less than the height at the top of the stack to maintain ascending order.
4fill in blank
hardComplete the code to complete the calculation of area and update max_area.
DSA C++
int area = height * [1]; max_area = std::max(max_area, area,);
Attempts:
3 left
💡 Hint
Common Mistakes
Using height instead of width for area calculation.
Missing comma in std::max causing syntax error.
✗ Incorrect
Area is height times width. max_area is updated by taking the maximum of current max_area and area.
5fill in blank
hardFill all three blanks to complete the final loop that processes remaining bars in the stack.
DSA C++
while (!stack.empty()) { int height = heights[stack.top()]; stack.pop(); int width = stack.empty() ? [1] : [2] - stack.top() - [3]; int area = height * width; max_area = std::max(max_area, area); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'i' instead of 'n' for width calculation.
Using 0 instead of 1 causing off-by-one error.
✗ Incorrect
When stack is empty, width is total bars 'n'. Otherwise, width is difference between 'n' and stack top minus 1.
