Array Insertion at End in DSA Python - Time & Space Complexity
We want to understand how long it takes to add an 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.
def insert_at_end(arr, value):
arr.append(value)
my_array = [1, 2, 3]
insert_at_end(my_array, 4)
print(my_array)
This code adds a new value to the end of the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding one item at the end of the array.
- How many times: Exactly once per insertion.
Adding one item at the end usually takes the same short time no matter how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays about the same as the array grows.
Time Complexity: O(1)
This means adding an item at the end takes a constant amount of time, no matter how big the array is.
[X] Wrong: "Adding at the end takes longer as the array grows because it has to move all items."
[OK] Correct: Arrays keep extra space at the end, so adding one item usually just places it there without moving others.
Knowing that adding at the end is fast helps you explain why some data structures are better for certain tasks.
"What if the array is full and needs to grow its size? How would the time complexity change then?"