Stack Concept and LIFO Principle in DSA Rust - Time & Space Complexity
We want to understand how fast stack operations run as the number of items grows.
How does adding or removing items affect the time it takes?
Analyze the time complexity of the following code snippet.
struct Stack {
items: Vec<i32>,
}
impl Stack {
fn push(&mut self, item: i32) {
self.items.push(item);
}
fn pop(&mut self) -> Option<i32> {
self.items.pop()
}
}
This code shows a stack using a vector, adding items on top and removing the last added item.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding or removing one item at the end of the vector.
- How many times: Each push or pop happens once per call, no loops inside.
Each push or pop takes about the same time no matter how many items are in the stack.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 operation per push or pop |
| 100 | 1 operation per push or pop |
| 1000 | 1 operation per push or pop |
Pattern observation: The time stays about the same no matter how big the stack is.
Time Complexity: O(1)
This means adding or removing an item takes the same short time regardless of stack size.
[X] Wrong: "Pushing or popping takes longer as the stack grows because it has more items."
[OK] Correct: The stack only adds or removes the last item, so it does not need to look at all items, keeping time constant.
Knowing stack operations run in constant time shows you understand efficient data handling, a key skill in many coding tasks.
"What if we changed the stack to remove items from the front instead of the end? How would the time complexity change?"
Practice
Solution
Step 1: Understand LIFO meaning
LIFO means the last item added to the stack is the first one to be taken out.Step 2: Match with options
Last In, First Out - the last element added is the first to be removed correctly states "Last In, First Out" which matches the LIFO principle.Final Answer:
Last In, First Out - the last element added is the first to be removed -> Option CQuick Check:
LIFO = Last In, First Out [OK]
- Confusing LIFO with FIFO
- Thinking first added is removed first
- Mixing up order of insertion and removal
stack?Solution
Step 1: Recall Rust Vec stack push method
In Rust, a stack is often implemented using a Vec, and pushing uses thepushmethod.Step 2: Check method names
Onlypushis the correct method to add an element at the end of a Vec.Final Answer:
stack.push(10); -> Option AQuick Check:
Rust Vec push method = push() [OK]
- Using add() which does not exist
- Using insert() without index
- Using append() which expects another collection
let mut stack = Vec::new();
stack.push(5);
stack.push(10);
let x = stack.pop();
println!("{:?}", x);
Solution
Step 1: Trace stack push operations
Stack after pushes: [5, 10] (10 is last pushed)Step 2: Trace pop operation
Pop removes last element 10 and returns Some(10) because pop returns Option type.Final Answer:
Some(10) -> Option AQuick Check:
pop() returns Some(last element) = Some(10) [OK]
- Thinking pop returns raw value, not Option
- Confusing order of elements popped
- Expecting None instead of Some value
let mut stack: Vec<i32> = Vec::new();
let value = stack.pop().unwrap();
println!("{}", value);Solution
Step 1: Understand pop() on empty Vec
pop() returns None if Vec is empty.Step 2: Effect of unwrap() on None
Calling unwrap() on None causes a runtime panic (crash).Final Answer:
Calling unwrap() on None causes panic -> Option BQuick Check:
unwrap() on None = panic [OK]
- Assuming pop() always returns Some
- Ignoring mutability requirement
- Misreading println! syntax
Operations: 1) push(1) 2) push(2) 3) pop() 4) push(3) 5) push(2) 6) pop()
Solution
Step 1: Simulate each operation step-by-step
Start: [] 1) push(1) -> [1] 2) push(2) -> [1, 2] 3) pop() removes 2 -> [1] 4) push(3) -> [1, 3] 5) push(2) -> [1, 3, 2] 6) pop() removes 2 -> [1, 3]Step 2: Compare final stack with options
Final stack is [1, 3], which matches Stack after operations is [1, 3].Final Answer:
Stack after operations is [1, 3] -> Option DQuick Check:
Trace pushes and pops carefully [OK]
- Ignoring pop removes last pushed element
- Mixing order of push and pop
- Assuming pop removes first element
Ready to prove it?
Pass the test and this pattern moves unknown
