Array Reversal Techniques in DSA Rust - Time & Space Complexity
We want to understand how the time it takes to reverse an array changes as the array gets bigger.
How does the number of steps grow when we reverse more items?
Analyze the time complexity of the following code snippet.
fn reverse_array(arr: &mut [i32]) {
let mut start = 0;
let mut end = arr.len().saturating_sub(1);
while start < end {
arr.swap(start, end);
start += 1;
end -= 1;
}
}
This code reverses the elements of an array by swapping pairs from the start and end moving towards the center.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Swapping two elements in the array.
- How many times: About half the length of the array (n/2) times.
As the array size grows, the number of swaps grows roughly half as fast.
| Input Size (n) | Approx. Operations (Swaps) |
|---|---|
| 10 | 5 |
| 100 | 50 |
| 1000 | 500 |
Pattern observation: The operations grow linearly with input size, just half as many swaps as elements.
Time Complexity: O(n)
This means the time to reverse the array grows directly in proportion to the number of elements.
[X] Wrong: "Reversing an array takes constant time because we just swap pairs."
[OK] Correct: Even though each swap is quick, the number of swaps grows with the array size, so total time grows too.
Understanding how simple loops like this scale helps you explain your code clearly and shows you know how to reason about performance.
"What if we used recursion to reverse the array instead? How would the time complexity change?"
Practice
Solution
Step 1: Understand array reversal
Reversing means flipping the order of elements so the last element comes first and the first element goes last.Step 2: Compare with other options
Sorting arranges elements by value, removing duplicates deletes repeats, and adding elements is insertion, not reversal.Final Answer:
Changing the order of elements so the last becomes first and first becomes last -> Option AQuick Check:
Reversal = Flip order [OK]
- Confusing reversal with sorting
- Thinking reversal removes elements
- Mixing reversal with adding elements
arr in place?Solution
Step 1: Identify correct method usage
In Rust, thereverse()method is called directly on a mutable slice or array asarr.reverse();to reverse it in place.Step 2: Check other options for errors
arr = arr.reverse(); tries to assign the result ofreverse()which returns (), so it's invalid. arr.reverse(&mut arr); passes&mut arras argument, butreverse()takes no arguments. reverse(arr); calls a functionreversewhich is undefined.Final Answer:
arr.reverse(); -> Option BQuick Check:
Use method directly on mutable array [OK]
- Assigning reverse() result to array
- Passing array as argument to reverse()
- Calling undefined reverse function
let mut arr = [1, 2, 3, 4, 5];
arr.reverse();
println!("{:?}", arr);Solution
Step 1: Understand reverse() effect on array
Thereverse()method reverses the array elements in place, so the order becomes last to first.Step 2: Apply reverse to given array
Original array is [1, 2, 3, 4, 5]. After reversal, it becomes [5, 4, 3, 2, 1].Final Answer:
[5, 4, 3, 2, 1] -> Option CQuick Check:
Reverse flips array order [OK]
- Expecting original order after reverse
- Thinking reverse sorts array
- Confusing output format
let arr = [10, 20, 30, 40]; arr.reverse();
Solution
Step 1: Check mutability of array
The arrayarris declared immutable by default withlet. Thereverse()method requires a mutable array.Step 2: Understand method requirements
To reverse in place, the array must be mutable, declared aslet mut arr. Otherwise, callingreverse()causes a compile error.Final Answer:
Cannot call reverse() on an immutable array -> Option AQuick Check:
reverse() needs mutable array [OK]
- Forgetting to add 'mut' to array declaration
- Thinking reverse() needs arguments
- Assuming reverse() is not available for arrays
vec = vec![1, 2, 3, 4, 5], which code snippet correctly reverses it and returns a new reversed vector without modifying the original?Solution
Step 1: Understand vector reversal without mutation
To reverse without changing original, use iteratorrev()oniter(), clone elements, then collect into new vector.Step 2: Analyze options
let rev_vec = vec.iter().rev().cloned().collect::(); usesvec.iter().rev().cloned().collect()which creates a new reversed vector. vec.reverse(); let rev_vec = vec.clone(); reverses original vector in place, modifying it. let rev_vec = vec.reverse(); tries to assignreverse()result which is (), invalid. let rev_vec = vec.into_iter().reverse().collect(); usesinto_iter()which consumes the original vector, so it doesn't leave the original unmodified.Final Answer:
let rev_vec = vec.iter().rev().cloned().collect::(); -> Option DQuick Check:
Use iter().rev().cloned().collect() for new reversed vector [OK]
- Modifying original vector instead of copying
- Assigning reverse() result directly
- Using invalid reverse() on iterator
Ready to prove it?
Pass the test and this pattern moves unknown
