Vector Size with len() and is_empty()
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
Three elements
Single element
Empty vector
Five elements
Three with negatives and zero
Algorithm Flow

Solution Approach
Best Answers
fn solution(nums: Vec<i32>) -> usize {
nums.len()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
