Array Deletion at Middle Index in DSA Python - Time & Space Complexity
When we delete an element from the middle 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_middle(arr):
mid = len(arr) // 2
for i in range(mid, len(arr) - 1):
arr[i] = arr[i + 1]
arr.pop()
# Deletes the middle element by shifting elements left
This code removes the middle element by shifting all elements after it one step to the left.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that shifts elements left after the middle index.
- How many times: It runs approximately n/2 times, where n is the array size.
As the array grows, the number of shifts grows roughly in half.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 5 shifts |
| 100 | About 50 shifts |
| 1000 | About 500 shifts |
Pattern observation: The work grows linearly with the size of the array.
Time Complexity: O(n)
This means the time to delete grows in a straight line as the array gets bigger.
[X] Wrong: "Deleting an element from the middle is always fast and takes constant time."
[OK] Correct: Because after deletion, elements must move to fill the gap, which takes time proportional to how many elements are shifted.
Understanding how array operations scale helps you explain trade-offs in data structures clearly and confidently.
"What if we deleted the last element instead of the middle? How would the time complexity change?"