Array Deletion at Beginning in DSA C - Time & Space Complexity
When we delete an element from the start of an array, the computer must adjust the rest of the elements.
We want to know how the time needed changes as the array gets bigger.
Analyze the time complexity of the following code snippet.
void deleteAtBeginning(int arr[], int *size) {
for (int i = 0; i < *size - 1; i++) {
arr[i] = arr[i + 1];
}
(*size)--;
}
This code removes the first element by shifting all other elements one position left.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that shifts elements left.
- How many times: It runs once for each element except the first, so roughly n-1 times.
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 roughly in a straight line 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 and takes constant time."
[OK] Correct: Because the array needs to move all other elements to fill the gap, which takes time proportional to the array size.
Understanding this helps you explain why some data structures are better for certain operations, showing your grasp of efficiency.
"What if we deleted the last element instead of the first? How would the time complexity change?"
