Array Access and Update at Index in DSA Python - Time & Space 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?
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 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.
Accessing or updating an element does not depend on the size of the array.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same no matter how big the array is.
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.
[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.
Knowing that array access and update are very fast helps you choose the right data structure for quick lookups and changes.
"What if we used a linked list instead of an array? How would the time complexity for access and update change?"