np.concatenate() for joining arrays in NumPy - Time & Space Complexity
When joining arrays using np.concatenate(), it is important to understand how the time needed grows as arrays get bigger.
We want to know how the work done changes when the input arrays increase in size.
Analyze the time complexity of the following code snippet.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.concatenate((arr1, arr2))
print(result)
This code joins two arrays into one longer array by placing the second array after the first.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Copying elements from each input array into a new larger array.
- How many times: Each element from both arrays is copied once.
As the total number of elements grows, the time to copy all elements grows roughly the same way.
| Input Size (total elements) | Approx. Operations (copies) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The time grows directly with the total number of elements to join.
Time Complexity: O(n)
This means the time to join arrays grows linearly with the total number of elements.
[X] Wrong: "Concatenating two arrays is instant and does not depend on their size."
[OK] Correct: The function must copy every element into a new array, so more elements mean more work and more time.
Understanding how array joining scales helps you explain performance in data processing tasks clearly and confidently.
"What if we concatenate a list of 10 arrays instead of just two? How would the time complexity change?"