Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a stack of integers for storing indices.
DSA C#
Stack<int> stack = new Stack<int>[1];Attempts:
3 left
💡 Hint
Common Mistakes
Using square brackets [] instead of parentheses for constructor.
Using curly braces {} which are for collection initializers.
✗ Incorrect
In C#, to create a new instance of a generic Stack, you use parentheses ().
2fill in blank
mediumComplete the code to push the current index i onto the stack.
DSA C#
stack.[1](i);Attempts:
3 left
💡 Hint
Common Mistakes
Using add or append which are not stack methods.
Using insert which is for lists.
✗ Incorrect
The method to add an element to the top of a stack in C# is Push().
3fill in blank
hardFix the error in the while loop condition to pop indices while the current price is higher.
DSA C#
while (stack.Count > 0 && prices[i] [1] prices[stack.Peek()]) { stack.Pop(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using < or <= which reverses the logic.
Using >= which includes equal prices incorrectly.
✗ Incorrect
We pop while current price is greater than price at top index to find previous higher price.
4fill in blank
hardFill both blanks to calculate the span correctly using stack top index.
DSA C#
span[i] = stack.Count == 0 ? i [1] 1 : i [2] stack.Peek();
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition when stack is empty.
Using multiplication or division which are incorrect here.
✗ Incorrect
If stack is empty, span is i+1; else span is difference between current and top index.
5fill in blank
hardFill all three blanks to complete the stock span function returning the span array.
DSA C#
public int[] CalculateSpan(int[] prices)
{
int n = prices.Length;
int[] span = new int[n];
Stack<int> stack = new Stack<int>[1];
for (int i = 0; i < n; i++)
{
while (stack.Count > 0 && prices[i] [2] prices[stack.Peek()])
stack.Pop();
span[i] = stack.Count == 0 ? i [3] 1 : i - stack.Peek();
stack.Push(i);
}
return span;
}Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting parentheses in stack constructor.
Using < instead of > in while condition.
Using - instead of + when stack is empty.
✗ Incorrect
Constructor uses (); condition uses >; span adds 1 when stack empty.
