Array Deletion at Beginning in DSA Python - Time & Space Complexity
When we delete an element from the start of an array, the time it takes depends on how many elements need to move.
We want to know how the work grows as the array gets bigger.
Analyze the time complexity of the following code snippet.
def delete_first_element(arr):
if len(arr) == 0:
return arr
for i in range(1, len(arr)):
arr[i - 1] = arr[i]
arr.pop()
return arr
This code removes the first element of the array by shifting all other elements one step left.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that shifts elements left by one position.
- How many times: It runs once for each element after the first, so roughly n-1 times for an array of size n.
As the array size grows, the number of shifts grows almost the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 9 shifts |
| 100 | 99 shifts |
| 1000 | 999 shifts |
Pattern observation: The work grows linearly with the number of elements.
Time Complexity: O(n)
This means the time to delete the first element grows directly with the array size.
[X] Wrong: "Deleting the first element is always fast because it's just one removal."
[OK] Correct: Because all other elements must move to fill the gap, which takes time proportional to the array size.
Understanding this helps you explain why some data structures are better for front deletions, showing your grasp of efficiency.
"What if we deleted the last element instead of the first? How would the time complexity change?"