Data Structures and Algorithms • C# examples
Time Complexity and Input Growth
Estimate algorithm running time by relating work to input size.
Concept
Time complexity describes how an algorithm’s work scales as input grows, rather than promising a specific number of milliseconds. A single pass is commonly linear, nested independent passes may be quadratic, and repeatedly halving a search interval is logarithmic. Count the dominant operations and define what n represents.
How to approach it
Count loop iterations or recursive subproblems, simplify the growth expression, and consider best, average, or worst cases where they differ.
Complexity
Typical families include O(1), O(log n), O(n), O(n log n), O(n²), and O(2ⁿ).
C# example
static bool Contains(IReadOnlyList<int> values, int target)
{
foreach (int value in values)
if (value == target) return true;
return false;
}
Expected result or behavior
At most n comparisons are made, so the worst-case running time grows linearly.
Practice exercise
Count the comparisons and iterations for a nested loop with bounds n and n - i.
Key takeaway: Complexity is a model of growth; state the input size and the case being analyzed.