Code Logo

Vector Size with len() and is_empty()

Published at25 Jul 2026
Rust Data Structures Easy 0 views
Like0

Write a Rust function that takes a vector of integers and returns the number of elements in it using the len() method. The len() method returns the current length (number of elements) of the vector as a usize.

The len() method is available on Vec, String, slices, and any type implementing the ExactSizeIterator trait. It returns the exact number of elements currently stored, which is separate from the vector's capacity. The length is maintained internally by the Vec as elements are added with push() or removed with pop().

Rust's len() is an O(1) operation because the vector stores its length as a field alongside the data pointer and capacity. This is in contrast to linked lists where computing length requires traversal. The is_empty() method is a convenience that checks if len() == 0 and is preferred for checking emptiness.

Time complexity is O(1) as len() simply reads a field from the Vec's internal structure. Space complexity is O(1). The method compiles to a single memory load instruction at the machine level.

Edge cases include empty vectors (len returns 0), vectors with one element, vectors with many elements, and ensuring the returned type is usize which is platform-dependent (64-bit on modern systems).

Example Input & Output

Example 1
Input
[1,2,3]
Output
3
Explanation

Three elements

Example 2
Input
[42]
Output
1
Explanation

Single element

Example 3
Input
[]
Output
0
Explanation

Empty vector

Example 4
Input
[10,20,30,40,50]
Output
5
Explanation

Five elements

Example 5
Input
[-1,0,1]
Output
3
Explanation

Three with negatives and zero

Algorithm Flow

Recommendation Algorithm Flow for Vector Size with len() and is_empty()
Recommendation Algorithm Flow for Vector Size with len() and is_empty()

Solution Approach

fn solution(nums: Vec<i32>) -> usize {
    nums.len()
}

Best Answers

rust - Approach 1
fn solution(nums: Vec<i32>) -> usize {
    nums.len()
}