Underlying numeric values in C Sharp (C#) - Time & Space Complexity
We want to understand how the time to get the numeric value behind a number type grows as the input changes.
How does the work change when we access or convert underlying numeric values?
Analyze the time complexity of the following code snippet.
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
{
int value = numbers[i];
int doubled = value * 2;
}
This code loops through an array of numbers, accesses each number, and doubles it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing each element in the array and multiplying it.
- How many times: Exactly once for each element, so n times.
As the number of elements grows, the work grows in a straight line with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times accessing and doubling |
| 100 | About 100 times accessing and doubling |
| 1000 | About 1000 times accessing and doubling |
Pattern observation: The work increases evenly as the input size increases.
Time Complexity: O(n)
This means the time to get and use each numeric value grows directly with the number of values.
[X] Wrong: "Accessing the underlying numeric value is instant and does not depend on the number of elements."
[OK] Correct: While accessing one value is quick, doing it many times adds up, so the total time grows with the number of elements.
Understanding how simple operations like accessing numeric values scale helps you reason about bigger problems and write efficient code.
"What if we replaced the array with a linked list? How would the time complexity change when accessing underlying numeric values?"