0
0
DSA Pythonprogramming~5 mins

Array Access and Update at Index in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array Access and Update at Index
O(1)
Understanding Time Complexity

We want to understand how fast we can get or change a value in an array at a certain position.

The question is: How does the time to access or update an element change as the array grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


arr = [10, 20, 30, 40, 50]
index = 2
value = arr[index]  # Access element at index 2
arr[index] = 100    # Update element at index 2

This code gets the value at position 2 and then changes it to 100.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Direct access to an array element by index.
  • How many times: Exactly once for access and once for update.
How Execution Grows With Input

Accessing or updating an element does not depend on the size of the array.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The number of operations stays the same no matter how big the array is.

Final Time Complexity

Time Complexity: O(1)

This means accessing or updating an element takes the same small amount of time no matter how big the array is.

Common Mistake

[X] Wrong: "Accessing an element takes longer if the array is bigger because it has to look through all elements."

[OK] Correct: Arrays allow direct access by index, so it jumps straight to the element without checking others.

Interview Connect

Knowing that array access and update are very fast helps you choose the right data structure for quick lookups and changes.

Self-Check

"What if we used a linked list instead of an array? How would the time complexity for access and update change?"