Array Deletion at End in DSA Python - Time & Space Complexity
We want to understand how fast it is to remove an item from the end of an array.
How does the time needed change as the array gets bigger?
Analyze the time complexity of the following code snippet.
def delete_at_end(arr):
if len(arr) == 0:
return None
return arr.pop()
This code removes the last item from the array if it exists.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Removing the last element using pop()
- How many times: Exactly once per call, no loops or recursion
Removing the last item takes the same amount of time no matter how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant as the array grows.
Time Complexity: O(1)
This means removing the last item takes the same short time no matter how big the array is.
[X] Wrong: "Removing the last item takes longer if the array is bigger because it has to shift elements."
[OK] Correct: When deleting at the end, no elements need to move. Only the last item is removed, so time stays the same.
Knowing that deleting at the end is very fast helps you choose the right data structure and method in real problems.
"What if we changed deletion to remove the first item instead? How would the time complexity change?"