Common Complexity Scenarios
Explore common time complexity scenarios involving various loop structures in C#. Learn how to calculate running times, including linear, quadratic, and logarithmic complexities, to better analyze and optimize algorithms for coding interviews.
List of important complexities
In this lesson, we’ll study some common examples and handy formulas for solving time complexity problems. The following list shows some common loop statements and how much time they take to execute.
Simple for loop
for (int x = 0; x < n; x++)
// statement(s) that take constant time
Running time complexity: .
Explanation: The C# for loop iterates through an array that contains integers from till (). During each iteration, x is assigned the value of the current number in the array. So, x is first , then , then , …, then . This means the loop runs a total of times; therefore, the running time complexity is .
The for loop with increments of size
for (int x = 0; x < n; x += k)
// statement(s) that take constant time
Running time complexity: = .
Explanation: The initialization x = 0; runs once. Then, x gets incremented by k until it reaches n. In other words, x is incremented to . Therefore, the incrementation part x += k of the for loop takes time. The comparison part of the for loop takes the same amount of time and one more iteration for the last comparison. So, this loop takes ...