Get Length of Linked List in DSA Rust - Time & Space Complexity
We want to understand how long it takes to find the length of a linked list as the list grows.
How does the time needed change when the list gets bigger?
Analyze the time complexity of the following code snippet.
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn get_length(head: &Option<Box<Node>>) -> usize {
let mut count = 0;
let mut current = head.as_ref();
while let Some(node) = current {
count += 1;
current = node.next.as_ref();
}
count
}
This code counts how many nodes are in a linked list by moving from the first node to the end.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that visits each node once.
- How many times: Exactly once per node in the list, from start to end.
As the list gets longer, the time to count nodes grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps to count nodes |
| 100 | 100 steps to count nodes |
| 1000 | 1000 steps to count nodes |
Pattern observation: The steps increase one-for-one with the number of nodes.
Time Complexity: O(n)
This means the time to find the length grows in direct proportion to the list size.
[X] Wrong: "Counting nodes is constant time because we just keep a count."
[OK] Correct: Even though counting is simple, we must visit each node to count it, so time grows with list length.
Knowing how to analyze simple linked list operations like length counting builds your confidence for more complex list problems.
"What if the linked list was doubly linked? Would the time complexity to get length change?"
Practice
Solution
Step 1: Understand the linked list traversal
The function starts at the head node and moves through each node one by one.Step 2: Count each node visited
For every node visited, the function increments a counter until it reaches the end (null).Final Answer:
Counts the number of nodes by traversing from head to end -> Option AQuick Check:
Length = number of nodes visited [OK]
- Returning the value of the first node instead of count
- Not handling empty list (null head)
- Trying to count without traversal
Solution
Step 1: Check struct initialization syntax
Rust structs are initialized with field names and values inside braces.Step 2: Match field names and order
let node = Node { value: 5, next: None }; uses correct field names and syntax. Tuple syntax requires tuple struct definition. Node::new(5) assumes an impl with new method. Omitting next field causes compile error.Final Answer:
let node = Node { value: 5, next: None }; -> Option CQuick Check:
Struct init uses field: value pairs [OK]
- Using tuple syntax for struct without tuple struct definition
- Missing field names in initialization
- Omitting required fields like next
struct Node {
value: i32,
next: Option,
}
fn length(head: &Option) -> usize {
let mut count = 0;
let mut current = head;
while let Some(node) = current {
count += 1;
current = &node.next;
}
count
}
fn main() {
let node3 = Node { value: 3, next: None };
let node2 = Node { value: 2, next: Some(Box::new(node3)) };
let node1 = Node { value: 1, next: Some(Box::new(node2)) };
let head = Some(Box::new(node1));
println!("{}", length(&head));
}Solution
Step 1: Understand the linked list structure
There are three nodes linked: node1 -> node2 -> node3 -> None.Step 2: Trace the length function
The function counts nodes by traversing from head. It visits node1, node2, and node3, incrementing count each time.Final Answer:
3 -> Option DQuick Check:
3 nodes counted [OK]
- Counting only head node
- Not dereferencing Option correctly
- Confusing Option with Box
fn length(head: &Option) -> usize {
let mut count = 0;
let mut current = head;
while current.is_some() {
count += 1;
current = current.unwrap().next;
}
count
}Solution
Step 1: Analyze unwrap usage on reference
Calling unwrap() on &Option tries to move out of a borrowed reference, which is not allowed.Step 2: Correct way to access next node
Use pattern matching or while let Some(node) = current to borrow without moving.Final Answer:
Using unwrap() on &Option causes a move error -> Option AQuick Check:
unwrap() moves ownership, not allowed on references [OK]
- Using unwrap() on borrowed Option causing move error
- Wrong loop condition logic
- Incorrect return type for length
fn length_even(head: &Option) -> usize {
// Your code here
}Solution
Step 1: Traverse the linked list nodes
Start from head and move through each node until None.Step 2: Check each node's value for evenness
Increment count only if node.value % 2 == 0 (even number).Step 3: Return the count of even-valued nodes
This gives the length of nodes with even values.Final Answer:
Traverse list, increment count only if node.value % 2 == 0 -> Option BQuick Check:
Count only even nodes by checking value % 2 == 0 [OK]
- Counting all nodes without filtering
- Assuming half nodes are even without check
- Using recursion without base case
Ready to prove it?
Pass the test and this pattern moves unknown
