Array indexing and access in C Sharp (C#) - Time & Space Complexity
When we access an element in an array by its position, we want to know how long it takes as the array grows.
We ask: Does it take longer to get an item if the array is bigger?
Analyze the time complexity of the following code snippet.
int[] numbers = {10, 20, 30, 40, 50};
int index = 3;
int value = numbers[index];
Console.WriteLine(value);
This code gets the value at position 3 in the array and prints it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing a single element by index.
- How many times: Exactly once, no loops or repeated steps.
Accessing an element by index takes the same 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 grows larger.
Time Complexity: O(1)
This means accessing any element by its position takes the same short time, no matter the array size.
[X] Wrong: "Accessing an element takes longer if the array is bigger because it has to look through all items."
[OK] Correct: Arrays allow direct access by position, so the computer jumps straight to the spot without checking others.
Knowing that array access is very fast helps you understand why arrays are useful and when to choose them in real projects.
"What if we used a linked list instead of an array? How would the time complexity of accessing an element by position change?"