Array Access and Update at Index in DSA C - 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.
int getValue(int arr[], int index) {
return arr[index];
}
void setValue(int arr[], int index, int value) {
arr[index] = value;
}
This code gets or sets a value at a specific index in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct access to an array element by index.
- How many times: Exactly once per call, no loops or recursion involved.
Accessing or updating an element takes the same amount of time no matter how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant even if the array size grows.
Time Complexity: O(1)
This means accessing or updating an element takes the same short 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 the computer jumps straight to the spot without checking others.
Knowing that array access and update are very fast helps you choose the right data structure and explain your choices clearly in interviews.
"What if we used a linked list instead of an array? How would the time complexity for access and update change?"
