Array Insertion at End in DSA C - Time & Space Complexity
We want to understand how long it takes to add a new item at the end of an array.
How does the time needed change as the array grows bigger?
Analyze the time complexity of the following code snippet.
void insertAtEnd(int arr[], int *size, int capacity, int value) {
if (*size < capacity) {
arr[*size] = value;
(*size)++;
}
}
This code adds a new value at the end of the array if there is space available.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Assigning the new value to the last position in the array.
- How many times: Exactly once per insertion.
Adding one item at the end always takes the same small number of steps, no matter how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same even if the array grows larger.
Time Complexity: O(1)
This means adding an item at the end takes a fixed amount of time regardless of array size.
[X] Wrong: "Adding at the end takes longer as the array gets bigger because we have to move all elements."
[OK] Correct: We do not move existing elements when adding at the end; we just place the new item in the next free spot.
Knowing that adding at the end is quick helps you explain why some data structures are faster for certain tasks.
"What if the array is full and we need to resize it before adding? How would the time complexity change?"
