Array Declaration and Initialization in DSA Python - Time & Space Complexity
When we create and fill an array, we want to know how long it takes as the array gets bigger.
We ask: How does the time to set up the array grow with its size?
Analyze the time complexity of the following code snippet.
n = 5
arr = [0] * n
for i in range(n):
arr[i] = i + 1
This code creates an array of size n and fills it with numbers from 1 to n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that sets each element in the array.
- How many times: It runs exactly n times, once for each element.
As the array size grows, the number of steps grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps to fill the array |
| 100 | 100 steps to fill the array |
| 1000 | 1000 steps to fill the array |
Pattern observation: Doubling the array size doubles the work needed to fill it.
Time Complexity: O(n)
This means the time to fill the array grows directly with its size.
[X] Wrong: "Creating and filling an array is instant and does not depend on size."
[OK] Correct: Each element must be set one by one, so bigger arrays take more time.
Understanding how array setup time grows helps you explain efficiency clearly in interviews.
"What if we initialize the array with a fixed value without a loop? How would the time complexity change?"