0
0
C Sharp (C#)programming~5 mins

Relational patterns in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Relational patterns
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list of numbers gets bigger, the program checks more numbers one by one.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in a straight line as the input list grows.

Common Mistake

[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.

Interview Connect

Understanding how loops and conditions affect speed helps you explain your code clearly and shows you know how programs grow with input.

Self-Check

"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?"