Stack Implementation Using Array in DSA C# - Time & Space Complexity
We want to understand how fast stack operations run when using an array.
How does the time to push or pop items change as the stack grows?
Analyze the time complexity of the following code snippet.
public class Stack {
private int[] arr;
private int top = -1;
private int capacity;
public Stack(int size) {
arr = new int[size];
capacity = size;
}
public void Push(int item) {
if (top == capacity - 1) throw new InvalidOperationException("Stack Overflow");
arr[++top] = item;
}
public int Pop() {
if (top == -1) throw new InvalidOperationException("Stack Underflow");
return arr[top--];
}
}
This code shows how to add (push) and remove (pop) items from a stack using an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single step to add or remove an item at the top index.
- How many times: Each push or pop does one operation regardless of stack size.
Each push or pop takes the same small amount of work no matter how many items are in the stack.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same even as the stack grows larger.
Time Complexity: O(1)
This means each push or pop operation takes a constant amount of time, no matter how big the stack is.
[X] Wrong: "Push or pop takes longer as the stack gets bigger because the array is bigger."
[OK] Correct: The operations only change one position at the top, so the size of the array does not affect the time.
Knowing that stack operations run in constant time shows you understand efficient data structures, a key skill in many coding challenges.
"What if the stack used a linked list instead of an array? How would the time complexity change?"
Practice
Solution
Step 1: Understand stack storage
A stack stores elements in order, last-in first-out, so it needs a structure to hold elements sequentially.Step 2: Role of array in stack
An array provides a fixed-size, ordered collection to hold stack elements efficiently.Final Answer:
To store elements in a fixed-size, ordered collection -> Option BQuick Check:
Stack uses array for fixed order storage [OK]
- Thinking array resizes automatically
- Confusing stack with queue behavior
- Assuming array sorts elements
Solution
Step 1: Recall C# array declaration syntax
In C#, arrays are declared with type[], variable name, and new type[size].Step 2: Match correct syntax
int[] stack = new int[5]; matches this pattern: int[] stack = new int[5];Final Answer:
int[] stack = new int[5]; -> Option AQuick Check:
C# array declaration = int[] name = new int[size]; [OK]
- Missing [] after type
- Using parentheses instead of brackets
- Incorrect variable declaration order
Push(10); Push(20); Pop(); Push(30); Pop(); Pop();
Assume the stack is initially empty and prints the popped values.
Solution
Step 1: Trace each operation step-by-step
Push(10) stack=[10]
Push(20) stack=[10,20]
Pop() removes 20, output=20, stack=[10]
Push(30) stack=[10,30]
Pop() removes 30, output=30, stack=[10]
Pop() removes 10, output=10, stack=[]Step 2: Collect popped outputs in order
The popped values printed are 20, then 30, then 10.Final Answer:
20 30 10 -> Option AQuick Check:
Stack LIFO pop order = 20 30 10 [OK]
- Confusing push and pop order
- Assuming FIFO instead of LIFO
- Missing last pop output
public void Push(int item) {
if (top == stack.Length) {
Console.WriteLine("Stack Overflow");
}
stack[top] = item;
top++;
}Solution
Step 1: Analyze overflow check logic
The code checks if top == stack.Length and prints overflow, but continues to assign and increment top anyway.Step 2: Identify missing control flow after overflow
Without a return or exit after overflow message, the code overwrites stack[top] causing error.Final Answer:
No return after overflow check causes overwrite -> Option CQuick Check:
Overflow check must stop push to avoid overwrite [OK]
- Assuming top comparison off by one
- Moving top++ before assignment causes wrong index
- Ignoring need to stop after overflow
Solution
Step 1: Understand array resizing in C#
Arrays have fixed size; to resize, create a new larger array and copy elements over.Step 2: Evaluate options for resizing stack array
Create a new array double the size, copy elements, then assign it to the stack variable correctly describes creating a new array double the size, copying elements, and reassigning stack variable.Final Answer:
Create a new array double the size, copy elements, then assign it to the stack variable -> Option DQuick Check:
Resize array by new array + copy + assign [OK]
- Assuming arrays can resize in place
- Using non-existent Resize method on arrays
- Overwriting data instead of resizing
Ready to prove it?
Pass the test and this pattern moves unknown
