Insert at End Tail Insert in DSA Rust - Time & Space Complexity
We want to understand how long it takes to add a new item at the end of a linked list.
How does the time needed change as the list grows bigger?
Analyze the time complexity of the following code snippet.
struct Node {
data: i32,
next: Option>,
}
fn insert_at_end(head: &mut Option>, value: i32) {
let mut current = head;
while let Some(ref mut node) = current {
current = &mut node.next;
}
*current = Some(Box::new(Node { data: value, next: None }));
}
This code adds a new node with the given value at the end of a singly linked list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that moves through each node to find the end.
- How many times: It runs once for each node in the list until it reaches the last node.
As the list gets longer, the loop runs more times because it must check each node to find the end.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to reach the end |
| 100 | About 100 steps to reach the end |
| 1000 | About 1000 steps to reach the end |
Pattern observation: The number of steps grows directly with the size of the list.
Time Complexity: O(n)
This means adding at the end takes longer as the list grows because we must check each node one by one.
[X] Wrong: "Adding at the end always takes the same time, no matter the list size."
[OK] Correct: Without a direct pointer to the last node, we must walk through all nodes, so time grows with list length.
Understanding this helps you explain why linked lists sometimes need extra pointers to be efficient.
It shows you can analyze how data structure design affects speed.
"What if we kept a pointer to the last node? How would the time complexity change?"
Practice
Solution
Step 1: Understand the operation name
"Insert at End" means adding a new element at the tail (last position) of the list.Step 2: Compare with other operations
Adding at the beginning is different; removing nodes is deletion, not insertion.Final Answer:
Adds a new node at the end of the list -> Option CQuick Check:
Insert at End = Add node at tail [OK]
- Confusing insert at end with insert at beginning
- Thinking it removes nodes instead of adding
- Mixing insertion with deletion operations
Solution
Step 1: Analyze code for tail insertion
let mut current = &mut head; while current.is_some() { current = &mut current.as_mut().unwrap().next; } *current = Some(Box::new(Node { value: 10, next: None })); traverses the list using mutable references until it finds None, then inserts the new node.Step 2: Check other options for correctness
head = Some(Box::new(Node { value: 10, next: head })); inserts at the head, not tail. head = None; clears the list. let mut current = &head; while current.is_some() { current = ¤t.unwrap().next; } current = Some(Box::new(Node { value: 10, next: None })); uses immutable references, causing compilation errors on unwrap() and rebinding, and doesn't modify the list.Final Answer:
The mutable reference traversal code correctly inserts at the end -> Option AQuick Check:
Mutable traversal + insert at None = tail insert [OK]
- Using immutable references when mutability is needed
- Inserting at head instead of tail
- Assigning to immutable references causing errors
struct Node {
value: i32,
next: Option,
}
fn main() {
let mut head: Option = None;
for val in [1, 2, 3] {
let mut current = &mut head;
while current.is_some() {
current = &mut current.as_mut().unwrap().next;
}
*current = Some(Box::new(Node { value: val, next: None }));
}
let mut current = &head;
while let Some(node) = current {
print!("{} -> ", node.value);
current = &node.next;
}
print!("null\n");
}Solution
Step 1: Trace insertion loop
The insertion loop correctly adds 1, then 2, then 3 at the tail, building 1 -> 2 -> 3 -> None.Step 2: Trace print loop
The print loop uses `let mut current = &head;` and `while let Some(node) = current` which causes a type mismatch because `current` is a reference to an Option, not an Option itself. To fix this, the code should use `current = current.as_ref().map(|node| &node.next)` or `while let Some(node) = current.as_ref()` to correctly traverse the list immutably. However, as given, the code will not compile due to this mismatch.Step 3: Correction
Assuming the print loop is fixed to use `while let Some(node) = current.as_ref()`, the output will be `1 -> 2 -> 3 -> null`.Final Answer:
1 -> 2 -> 3 -> null -> Option BQuick Check:
Tail insertion preserves order; print loop needs as_ref() for immutable traversal [OK]
- Type mismatch between `&Option` and `Option` in pattern matching
- Forgetting `as_ref()` for immutable list traversal
- Confusing head insertion (reverses order) with tail insertion
let mut current = &head;
while current.is_some() {
current = ¤t.unwrap().next;
}
*current = Some(Box::new(Node { value: 5, next: None }));Solution
Step 1: Identify reference mutability
Variable `current` is an immutable reference to `head`, so `*current = ...` is invalid.Step 2: Understand Rust's mutability rules
To modify the list, `current` must be a mutable reference (`&mut`).Final Answer:
Cannot assign to `*current` because `current` is an immutable reference -> Option AQuick Check:
Mutable reference needed for assignment [OK]
- Using immutable references when mutability is required
- Ignoring Rust's ownership and borrowing rules
- Assuming unwrap causes error here instead of mutability
Solution
Step 1: Handle empty list case
If head is None, assign the new node directly to head to start the list.Step 2: Handle non-empty list case
If head exists, traverse to the last node and insert the new node at the end.Final Answer:
Check if head is None, then assign new node directly to head; else traverse to tail and insert -> Option DQuick Check:
Empty list needs direct head assignment [OK]
- Not checking for empty list causing panic
- Overwriting head without condition
- Using recursion incorrectly for tail insertion
Ready to prove it?
Pass the test and this pattern moves unknown
