Array Reversal Techniques in DSA Python - Time & Space Complexity
We want to understand how the time needed to reverse an array changes as the array gets bigger.
How does the number of steps grow when we reverse more elements?
Analyze the time complexity of the following code snippet.
def reverse_array(arr):
start = 0
end = len(arr) - 1
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
This code reverses the elements of an array by swapping pairs from the ends 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 array reversal scales helps you reason about loops and data manipulation, a key skill in many coding challenges.
"What if we used recursion to reverse the array instead of a loop? How would the time complexity change?"