0
0
DSA Pythonprogramming~5 mins

Array Declaration and Initialization in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array Declaration and Initialization
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array size grows, the number of steps grows in the same way.

Input Size (n)Approx. Operations
1010 steps to fill the array
100100 steps to fill the array
10001000 steps to fill the array

Pattern observation: Doubling the array size doubles the work needed to fill it.

Final Time Complexity

Time Complexity: O(n)

This means the time to fill the array grows directly with its size.

Common Mistake

[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.

Interview Connect

Understanding how array setup time grows helps you explain efficiency clearly in interviews.

Self-Check

"What if we initialize the array with a fixed value without a loop? How would the time complexity change?"