Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 24

    Big-O for .NET Developers: Time and Space in LINQ

    Big-O for .NET developers describes how time and space costs grow. For LINQ, count the work done when a query runs and the extra storage it needs.

    The method is the same for loops and LINQ: name the input sizes, state what each operation costs, and combine those costs. Time and storage need separate answers.

    How do you choose the input size and cost model?

    The programs below count visits, tests, and stored elements. These counts describe work and storage, not elapsed milliseconds.

    Before calculating anything, name the inputs. For example:

    • Let n be the number of orders.
    • Let m be the number of allowed customer IDs.
    • Let k be the number of orders returned.

    Keep those names separate. An order collection can grow without the allowed-ID collection growing.

    Next, state your cost model: which operations you will treat as one bounded amount of work. In this lesson, reading an array element, comparing two integers, and adding two integers cost O(1). The examples use small values that do not overflow.

    Do not silently extend that assumption to every type. Comparing long strings can require reading many characters. A method called once per element might itself scan another collection.

    This lesson considers LINQ running over in-memory .NET collections. A query translated into SQL needs a different analysis.

    The mistake to avoid. Do not give a bound before saying what grows and what you are counting. “O(n)” is incomplete when nobody knows what n represents.

    In an interview, say: “I first define the input sizes and the operations I am counting. I then calculate how that work grows. I give separate answers for time and extra storage rather than predicting milliseconds.”

    What do O(1), O(log n), O(n), O(n log n), and O(n²) mean?

    These bounds describe different patterns of growth:

    BoundPlain meaningExample under our cost model
    O(1), constantWork stays bounded as the input grows.Read one array element at a known valid index.
    O(log n), logarithmicRepeatedly reducing the remaining problem by a fixed factor gives slowly growing work.List<T>.BinarySearch repeatedly halves a sorted search range.
    O(n), linearWork grows in proportion to input size.Visit every element once.
    O(n log n), linearithmicWork grows like n multiplied by log n.Sorting with OrderBy or List<T>.Sort under constant-cost comparisons, in the worst case too.
    O(n²), quadraticWork grows in proportion to the square of input size.Visit all n elements for each of n elements.

    For the LINQ sorting operator, see the OrderBy reference. The List<T>.Sort documentation describes its sorting algorithm and complexity.

    For a halving process, doubling the input adds roughly one more step. For a linear scan, doubling the input roughly doubles the counted work. For a quadratic scan, it roughly quadruples it.

    These comparisons describe the growth pattern, not a stopwatch result. An O(n) implementation can be slower than an O(n²) implementation on a small input because each operation costs more.

    The mistake to avoid. O(1) does not mean “one instruction,” and a better growth bound does not guarantee a faster implementation for every input size.

    In an interview, say: “Constant work stays bounded. Logarithmic work grows through repeated reductions, linear work follows the input size, linearithmic work follows n times log n, and quadratic work follows n squared. These describe scaling, not exact speed.”

    How do consecutive loops and nested loops combine?

    Add work that happens one part after another. Multiply when every outer iteration performs a full inner scan.

    Predict the two counts before running this program:

    C#Runs
    int[] orders = { 10, 20, 30, 40 };
    int[] allowedIds = { 1, 2, 3 };
    
    long consecutiveVisits = 0;
    foreach (int order in orders)
        consecutiveVisits++;
    foreach (int id in allowedIds)
        consecutiveVisits++;
    
    long pairVisits = 0;
    foreach (int order in orders)
    {
        foreach (int id in allowedIds)
            pairVisits++;
    }
    
    Console.WriteLine($"Consecutive visits: {consecutiveVisits}");
    Console.WriteLine($"Nested pair visits: {pairVisits}");
    Output
    Consecutive visits: 7
    Nested pair visits: 12

    The first part visits four orders, then three IDs. It performs n + m visits: seven here. Its time is O(n + m).

    The second part visits all three IDs for each of four orders. It performs n × m visits: twelve here. Its time is O(n·m).

    If both loops scan the same n elements consecutively, their total is 2n, which simplifies to O(n). If both full nested scans have size n, their product is O(n²).

    This reasoning also applies inside LINQ. A query that performs a full scan of m IDs for every one of n orders does O(n·m) work. Writing the scans in one expression does not remove either scan.

    The mistake to avoid. Do not turn O(n·m) into O(n²) unless the two sizes are the same, or you explicitly choose a shared bound. Independent inputs belong in the answer.

    In an interview, say: “I add consecutive costs and multiply full nested scans. Two scans of n are O(n). Scanning m items for each of n items is O(n·m), becoming O(n²) when both sizes are n.”

    How do time complexity and extra-space complexity differ in LINQ?

    The running-total example below keeps one total. The filtering example keeps a list of matching values. We count this additional storage separately from the work.

    State whether you include the returned result. Here, we include it and exclude the input array.

    Where tests elements and passes on those that match. ToList consumes its source and stores the resulting elements in a new list.

    Predict the total, predicate-call count, and result count:

    C#Runs
    int[] values = { 1, 2, 3, 4, 5, 6 };
    
    int total = 0;
    foreach (int value in values)
        total += value;
    
    int predicateCalls = 0;
    var evens = values.Where(value =>
    {
        predicateCalls++;
        return value % 2 == 0;
    }).ToList();
    
    Console.WriteLine($"Running total: {total}");
    Console.WriteLine($"Filter tests: {predicateCalls}");
    Console.WriteLine($"Stored matches: {evens.Count}");
    Output
    Running total: 21
    Filter tests: 6
    Stored matches: 3

    The running total is 21. It reads six values and keeps one accumulator. Its time is O(n), and its extra space is O(1).

    The filter tests all six values and stores three matches. With a constant-cost test, its time is O(n), including building the result. If k elements match, the result requires O(k) storage, plus bounded query bookkeeping. In the worst case, all elements match, so extra space is O(n).

    flowchart TD
        I["Existing input"] -->|"is scanned by"| T["Running total"]
        I -->|"is scanned by"| F["Filter and ToList"]
        T -->|"retains"| A["One accumulator"]
        F -->|"retains"| R["k matching elements"]

    Both paths read the input, but the filtered result retains storage that grows with the number of matches.

    If the interviewer excludes output storage, report the result separately instead of silently changing conventions.

    While ToList builds its result, it can also hold temporary storage for a moment. This is still O(k) extra space, because that storage is at most a constant times the size of the result.

    The streaming operators lesson examines what changes when you consume matches without collecting them.

    The mistake to avoid. A single pass does not imply O(1) extra space. Keeping every matching element can require O(n) storage even though each input element is visited once.

    In an interview, say: “Both examples scan n values, but their storage differs. A running total uses O(1) extra space; collecting up to n matches uses O(n). I state whether I include output storage.”

    Why is List<T>.Add O(1) amortized?

    These kinds of bounds answer different questions:

    • Best-case complexity describes the cheapest input or operation of a given size.
    • Worst-case complexity bounds the most expensive input or operation of a given size.
    • Average-case complexity is the cost averaged over an assumed mix of inputs, for example when every possible input is equally likely.
    • Amortized complexity spreads the total cost across a sequence of operations, without assuming random inputs.

    List<T>.Add is a useful example of the last kind, amortized cost. A list's capacity is the number of elements its current internal array can hold.

    When there is spare capacity, adding an element is O(1). When the array is full, the list allocates a larger array and copies the existing elements. That individual addition is O(n), where n is the current count. The Add documentation states both costs.

    The following program counts additions and infers copied elements from capacity changes. It does not measure allocated bytes or elapsed time.

    C#Runs
    foreach (int size in new[] { 16, 32 })
    {
        var values = new List<int>();
        long copiedElements = 0;
        int growthEvents = 0;
    
        for (int i = 0; i < size; i++)
        {
            int oldCount = values.Count;
            int oldCapacity = values.Capacity;
            values.Add(i);
    
            if (values.Capacity != oldCapacity)
            {
                growthEvents++;
                copiedElements += oldCount;
            }
        }
    
        Console.WriteLine($"Items: {size}; capacity: {values.Capacity}");
        Console.WriteLine($"Growth events: {growthEvents}; inferred copies: {copiedElements}");
        Console.WriteLine($"Writes plus copies: {size + copiedElements}");
    }
    Output
    Items: 16; capacity: 16
    Growth events: 3; inferred copies: 12
    Writes plus copies: 28
    Items: 32; capacity: 32
    Growth events: 4; inferred copies: 28
    Writes plus copies: 60

    Each iteration writes one new element. When capacity changes, oldCount elements must also be copied, according to the documented growth behavior.

    The observed capacities are runtime-specific, not a public promise. The .NET 10 List implementation starts growth at four slots and normally doubles capacity, subject to size limits and required capacity.

    This is geometric growth: capacity grows by a fixed factor rather than one slot at a time. With doubling, the copied element counts form a series such as 4 + 8 + 16 + .... Their total stays proportional to the final number of elements. In the output, 16 items cost 28 writes plus copies, and 32 items cost 60. Doubling n roughly doubles the counted total. For these two sizes, both totals are under 2n.

    Consequently, n additions to an initially empty list take O(n) total work, or O(1) amortized per addition. Allocating and initializing the replacement arrays also fits that linear total. Peak extra storage is O(n).

    The mistake to avoid. “O(1) amortized” does not mean every call is O(1), and it is not an average over lucky and unlucky inputs. One resize can still take O(n).

    In an interview, say: “Best and worst cases describe the cheapest and most expensive inputs of a given size. Average case uses an assumed mix of inputs. Amortized cost averages work across a sequence of operations, with no probability assumption. List.Add is O(1) within capacity and O(n) when resizing. Geometric growth makes it O(1) amortized per addition.”

    How do helper collections change the total complexity?

    A helper collection can reduce repeated work, but you must pay to build and store it.

    A HashSet<T> stores distinct values. Hashing computes a code used to narrow where a value is searched for. A collision occurs when different values lead to the same hash code, so equality checks must distinguish them.

    For this example, assume constant-cost integer hashing and equality, with well-distributed hashes. Under those assumptions, set lookups have expected O(1) cost. The HashSet<T>.Contains documentation describes membership testing as an O(1) operation. “Expected” is a statement about average behavior under the hashing assumptions, not a worst-case guarantee.

    C#Runs
    int[] orders = { 1, 2, 3, 4, 2 };
    int[] allowedIds = { 2, 4 };
    
    var allowed = new HashSet<int>(allowedIds);
    int matches = 0;
    int probes = 0;
    
    foreach (int order in orders)
    {
        probes++;
        if (allowed.Contains(order))
            matches++;
    }
    
    Console.WriteLine($"Input IDs to build from: {allowedIds.Length}");
    Console.WriteLine($"Membership probes: {probes}");
    Console.WriteLine($"Matching orders: {matches}");
    Output
    Input IDs to build from: 2
    Membership probes: 5
    Matching orders: 3

    A probe is one membership request; it is not a count of the comparisons performed inside the set.

    For m allowed IDs and n orders, the complete calculation is:

    • Build the set: expected O(m) time. It uses O(m) extra space, because it stores at most m distinct IDs.
    • Check all orders: expected O(n) time.
    • Total under this model: process m construction inputs and make n membership probes, giving expected O(n + m) time and O(m) extra space.

    Collision-heavy hashing can make a lookup scan many stored candidates. Therefore, the expected bound must not be presented as an unconditional worst-case bound.

    Read the HashSet documentation for its set operations. The nested queries versus HashSet lesson develops the lookup trade-off further.

    The mistake to avoid. Do not report only O(n) lookup work while ignoring the O(m) construction and storage. Reusing an already-built set is a different starting assumption.

    In an interview, say: “With suitable hashing and constant-cost equality, building the set and probing it gives expected O(m + n) time and O(m) extra space. I include construction, and I do not claim hashing guarantees constant-time lookups in the worst case.”

    Can two O(n) LINQ queries have different performance?

    Yes. A constant factor is a multiplier that does not grow with the input size. Big-O drops that multiplier, but the processor still does the work.

    Compare two fully consumed queries. Each tests every input element, but the second deliberately repeats its per-element work.

    C#Runs
    int[] values = { 1, 2, 3, 4, 5, 6 };
    
    int cheapTests = 0;
    int cheapMatches = values.Count(value =>
    {
        cheapTests++;
        return value % 2 == 0;
    });
    
    int repeatedTests = 0;
    int repeatedMatches = values.Count(value =>
    {
        bool even = false;
        for (int repeat = 0; repeat < 10; repeat++)
        {
            repeatedTests++;
            even = value % 2 == 0;
        }
        return even;
    });
    
    Console.WriteLine($"First: matches={cheapMatches}; tests={cheapTests}");
    Console.WriteLine($"Second: matches={repeatedMatches}; tests={repeatedTests}");
    Output
    First: matches=3; tests=6
    Second: matches=3; tests=60

    Here, Count(predicate) evaluates the condition across the source and counts matches.

    Their counted work is n and 10n, so both are O(n). The inner loop does not make the second query quadratic: its limit is the fixed number ten, not n.

    These counters justify growth bounds, not timing claims. Actual performance also depends on allocations, work inside each call, and runtime optimizations. Measurements on representative inputs are needed to compare elapsed time.

    Repeatedly creating and discarding temporary objects can allocate many bytes without needing all of them simultaneously. Detailed allocation measurement belongs in the allocation lesson.

    The mistake to avoid. Neither equal Big-O bounds nor source-level operation counts prove equal running time. The counting code we added also does work, so these counters are not a benchmark.

    In an interview, say: “Two O(n) algorithms can have different constants, per-element work, allocations, and runtime optimizations. Big-O compares growth. I measure representative inputs to compare actual running time.”

    Check yourself

    A query scans n orders and, for every order, scans all m allowed IDs. What is its time complexity under constant-cost comparisons?

    A O(n + m)
    B O(n·m)
    C O(n²), regardless of m
    D O(1), because it is one query
    Show answer

    Correct answer: B

    Every one of the n orders triggers m comparisons. Keep the two independent input sizes unless the problem states a relationship between them.

    A List<int> starts empty and grows geometrically while n elements are added. Which statement is correct?

    A Each Add costs O(1) even in the worst case, including resizes.
    B n additions require O(n²) total work, since each resize copies the list.
    C n additions take O(n) total, though a single resizing Add can cost O(n).
    D Amortized O(1) can fail when input values arrive in sorted order.
    Show answer

    Correct answer: C

    Geometric growth keeps total copying proportional to n. Amortized analysis spreads that total over the additions without assuming random input values.

    Going deeper

    A nested loop does not automatically mean quadratic work. If its inner limit depends on the outer index, count the actual visits. For example, 1 + 2 + ... + n still grows quadratically. If the inner loop halves a range of size n each step, it costs O(log n), so running it for each of n outer items costs O(n log n).

    Your element-cost assumptions can also introduce another input size. If each comparison can inspect up to L characters, include that cost rather than treating every string comparison as O(1).

    For space analysis, count storage that is needed at the same time. During a resize, the old and replacement arrays coexist while copying occurs. Unreachable arrays awaiting garbage collection are a separate concern from the algorithm's live-storage requirement.

    If you know a useful size estimate, setting initial collection capacity can avoid repeated reallocations. The .NET collections guidance recommends this approach, but reserving capacity is still a storage decision, not free memory.

    Finally, distinguish creating a LINQ query from consuming it. The examples here force the relevant work to happen. Continue with deferred execution and multiple enumeration to analyze when that work happens and when it happens again.

    A complete answer for the set-based approach is: “Inputs: n orders and m IDs. Assumptions: O(1) integer comparison and hashing, with well-distributed hashes. Time: expected O(n + m), including set construction. Extra space: O(m) for the set. If I also collect k matching orders, it is O(m + k). With heavy collisions, construction can cost O(m²), and checking all orders can cost O(n·m), giving O(m² + n·m) total worst-case time.”

    Sources

    Practice

    Practice test: LINQ Complexity Practice: Count the Work and the Space5 questions · 1 mark each, no negative marking
    Take the test
    Practice: Big-O for .NET Developers: Time and Space in LINQ9 questions · 9 marks
    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 28 Nov 2026 ·