Constant patterns in C Sharp (C#) - Time & Space Complexity
Let's look at how some code runs in a way that doesn't change with input size.
We want to see what happens when the steps stay the same no matter how big the input is.
Analyze the time complexity of the following code snippet.
int MultiplyByTwo(int number)
{
int result = number * 2;
return result;
}
int value = 10;
int doubled = MultiplyByTwo(value);
Console.WriteLine(doubled);
This code multiplies a single number by two and prints the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One multiplication and one return.
- How many times: Exactly once, no loops or repeats.
Since the code does the same steps no matter the input size, the work stays steady.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 (multiply, assign, return) |
| 100 | 3 (same steps) |
| 1000 | 3 (still the same steps) |
Pattern observation: The number of steps does not increase with input size; it stays constant.
Time Complexity: O(1)
This means the code takes the same amount of time no matter how big the input is.
[X] Wrong: "If the input number is bigger, the code will take longer to run."
[OK] Correct: The code does just one multiplication and return, so input size does not affect the steps.
Understanding constant time helps you recognize when code runs quickly and predictably, a useful skill in many coding tasks.
"What if we added a loop that runs 'number' times inside the function? How would the time complexity change?"