Relational patterns in C Sharp (C#) - Time & Space Complexity
We want to understand how fast a program runs when it uses relational patterns in C#.
Specifically, we ask: how does the program's work grow when the input changes size?
Analyze the time complexity of the following code snippet.
int[] numbers = {1, 5, 10, 15, 20};
int threshold = 10;
foreach (int num in numbers)
{
if (num is > threshold)
{
Console.WriteLine($"{num} is greater than {threshold}");
}
}
This code checks each number to see if it is greater than a threshold and prints it if true.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every number in the array.
As the list of numbers gets bigger, the program checks more numbers one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the program takes longer in a straight line as the input list grows.
[X] Wrong: "Relational patterns make the program faster because they are special checks."
[OK] Correct: Relational patterns are just a way to write conditions clearly; the program still checks each item one by one.
Understanding how loops and conditions affect speed helps you explain your code clearly and shows you know how programs grow with input.
"What if we replaced the array with a sorted list and stopped checking after the first number greater than the threshold? How would the time complexity change?"