Bird
0
0
DSA Cprogramming~5 mins

Array Access and Update at Index in DSA C - 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.


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 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 per call, no loops or recursion involved.
How Execution Grows With Input

Accessing or updating an element takes the same amount of time no matter how big the array is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays constant even if the array size grows.

Final Time Complexity

Time Complexity: O(1)

This means accessing or updating an element takes the same short 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 the computer jumps straight to the spot without checking others.

Interview Connect

Knowing that array access and update are very fast helps you choose the right data structure and explain your choices clearly in interviews.

Self-Check

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