Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    DSA Coding Patterns in C#: back to the course
    Lesson2 / 20

    The C# Angle: Collection Costs, LINQ Costs, Strings and Span in Coding Interviews

    Choose C# collections by the operations your solution repeats. LINQ, strings and Span can change both the time cost and memory cost of a coding interview solution.

    This lesson builds on solving and checking a coding problem. We will connect familiar APIs to the work they actually perform.

    Which C# collection should I choose?

    Start with the operation you need, not the collection you use most often.

    Average-case and worst-case describe different costs:

    • Average-case describes expected work under assumptions about the inputs, such as well-distributed hash codes.
    • Worst-case describes the largest cost for one operation at the stated size.

    A collision is two different keys with the same hash code; many collisions slow hash lookups (see hashing patterns).

    When a List<T> is full, Add copies its items into a larger array, usually about twice as large. That particular addition costs O(n). Across n additions, the total work is O(n), or O(1) per addition when spread across the sequence. This is called amortized O(1); it is not a probability claim. See List.Add and capacity growth.

    In this table, n is the current collection size. Costs assume constant-time comparisons and hash calculations unless stated otherwise.

    NeedTypeImportant costs and limits
    Fixed-size indexed storageT[]Index access O(1); unsorted search O(n)
    Growable indexed storageList<T>Index O(1); Add amortized O(1), O(n) when it grows; Insert, RemoveAt and Contains O(n)
    Key-to-value lookupDictionary<TKey,TValue>Lookup, add and remove expected O(1) with good hashing; O(n) with many collisions
    Membership or unique valuesHashSet<T>Add, Contains and Remove expected O(1) with good hashing; O(n) with many collisions
    First-in, first-out processingQueue<T>Dequeue O(1); enqueue amortized O(1), worst-case O(n)
    Last-in, first-out processingStack<T>Pop O(1); push amortized O(1), worst-case O(n)
    Repeatedly take the smallest priorityPriorityQueue<TElement,TPriority>Peek O(1); Dequeue O(log n); Enqueue amortized O(log n), O(n) when storage grows; Remove of a given element (.NET 9+) O(n)
    Keep keys sorted while updatingSortedDictionary<TKey,TValue>Lookup, insertion and removal O(log n)
    Compact sorted key/value storageSortedList<TKey,TValue>Key lookup O(log n); arbitrary insertion/removal O(n)
    Sorted unique valuesSortedSet<T>Lookup, insertion and removal O(log n)
    Insert/remove beside a known nodeLinkedList<T>Known-node insertion/removal O(1); finding that node O(n); no indexed access
    Count a small, fixed value rangeint[]Increment/read a counter O(1); storage O(range size)

    A linked-list node holds an element and links to neighboring nodes. With the node in hand, removal only changes those links; without it, you must first walk the list to find it.

    A fixed counting array uses values as indexes. For lowercase English letters, for example, index c - 'a' selects one of 26 counters. Validate that input restriction first.

    Why not use a list as a queue? Removing index zero shifts all remaining elements, while Queue<T> removes the oldest item in O(1); see queues in C#.

    Both sorted dictionary types maintain sorted keys. SortedDictionary suits frequent updates to unsorted input. SortedList uses compact arrays and usually less memory, but arbitrary insertion and removal require shifting. See Microsoft's sorted dictionary comparison and collection guidance.

    The mistake to avoid. Do not choose LinkedList for cheap removal unless you already have the node. Likewise, repeated List.RemoveAt(0) calls can make draining a list quadratic.

    In an interview, say: “List.Add is usually O(1). When capacity runs out, it copies into a larger array, usually about double, costing O(n). Across n additions, total work is O(n), so each addition is amortized O(1). For first-in, first-out processing, I use a queue rather than repeatedly shifting a list.”

    Why can List.Contains make a loop quadratic?

    A library call inside a loop contributes to the loop's total cost.

    Guess whether these two approaches produce the same unique count:

    C#Runs
    int[] input = { 4, 2, 4, 3, 2 };
    var list = new List<int>();
    foreach (int value in input)
    {
        if (!list.Contains(value))
            list.Add(value);
    }
    
    var set = new HashSet<int>();
    foreach (int value in input)
        set.Add(value);
    
    Console.WriteLine($"List unique count: {list.Count}");
    Console.WriteLine($"Set unique count: {set.Count}");
    Output
    List unique count: 3
    Set unique count: 3

    Both loops keep the same 3 values, at different costs. List.Contains scans the list, so the list version makes up to 0 + 1 + ... + (n − 1) comparisons: O(n²).

    The set performs n additions, each average O(1) with suitable hashing. Total expected work is O(n), with O(n) storage. Poor hashing can make an individual operation O(n), so this is not a worst-case linear guarantee.

    For membership checks against an existing list, building a separate set also costs time and additional storage. That setup is worthwhile when enough repeated searches follow.

    Continue with dictionary and HashSet patterns for choosing keys and handling poor hash codes.

    The mistake to avoid. A single visible loop does not prove O(n). Add up the costs of the members called on each iteration.

    In an interview, say: “List.Contains is O(n). HashSet.Contains is average O(1) with suitable hashing. Across n checks on growing collections, that can mean O(n²) versus average O(n), at the cost of additional storage.”

    How should I sort values and compare keys?

    A comparer defines ordering. An equality comparer decides whether two keys count as the same key and supplies compatible hash codes.

    A sort is stable when items with equal sort keys keep their original relative order. Array.Sort and List.Sort are unstable. LINQ's OrderBy is stable.

    LINQ provides operations over sequences. Deferred execution means creating a query does not yet perform its traversal. Fully enumerating an OrderBy query requires buffering: retaining the input while arranging its order.

    In .NET, a culture is a language-and-region setting, such as en-US or tr-TR. Culture-aware string sorting follows language-specific rules. Ordinal comparison compares character codes instead. Use StringComparer.Ordinal, or OrdinalIgnoreCase when the problem ignores case. Default string sorting is culture-aware; ordinary string equality is ordinal.

    Predict the two name orders:

    C#Runs
    var entries = new[] { (Score: 5, Name: "b"), (Score: 5, Name: "a") };
    Console.WriteLine(string.Join(",", entries.OrderBy(x => x.Score).Select(x => x.Name)));
    
    Array.Sort(entries, (x, y) =>
    {
        int byScore = x.Score.CompareTo(y.Score);
        return byScore != 0 ? byScore : StringComparer.Ordinal.Compare(x.Name, y.Name);
    });
    Console.WriteLine(string.Join(",", entries.Select(x => x.Name)));
    Output
    b,a
    a,b

    The stable sort preserves b,a. The explicit name tie-breaker produces a,b, without depending on stability.

    Use CompareTo, not subtraction, for numeric comparisons: x.Score - y.Score can overflow and give the wrong ordering.

    As set or dictionary keys, tuples compare by their values and arrays by reference; see choosing hash keys.

    Read more about Array.Sort stability, OrderBy and string comparison rules. Sorting and Selection in C# shows each of these traps in depth.

    The mistake to avoid. Sorting rules and key-equality rules are part of correctness. Do not let an unspecified tie order, current culture or array identity silently choose the answer.

    In an interview, say: “Array.Sort and List.Sort are unstable; OrderBy is stable but deferred and buffers for full ordering. I use a tie-breaker when needed, CompareTo for numbers, and ordinal string comparison unless the task requires linguistic rules.”

    What order do C# collections enumerate in?

    Enumeration means visiting a sequence through operations such as foreach. A collection's lookup behavior does not necessarily promise an iteration order.

    A Dictionary guarantees no enumeration order. Do not depend on insertion order you happen to observe. Sort its keys or choose a sorted collection for ordered output.

    A Stack enumerates top-first. A Queue enumerates oldest-first. A priority queue's UnorderedItems does not enumerate in priority order; repeatedly dequeue to obtain that order.

    C#Runs
    var stack = new Stack<int>();
    stack.Push(1);
    stack.Push(2);
    stack.Push(3);
    Console.WriteLine($"Stack: {string.Join(",", stack)}");
    
    var scores = new Dictionary<string, int>(StringComparer.Ordinal)
    {
        ["b"] = 2,
        ["a"] = 1
    };
    foreach (string key in scores.Keys.OrderBy(k => k, StringComparer.Ordinal))
        Console.WriteLine($"{key}: {scores[key]}");
    Output
    Stack: 3,2,1
    a: 1
    b: 2

    The stack prints 3,2,1; enumeration does not pop those values. Sorting the dictionary keys makes the output explicitly a before b.

    Mutation rules depend on both the collection and the operation. Adding, removing or replacing list elements during its foreach (even list[i] = x) invalidates enumeration. The next loop step throws InvalidOperationException, reporting that the collection was modified. You can instead remove items with a backwards for loop, use RemoveAll, or collect changes and apply them after the loop. See List.GetEnumerator.

    This check demonstrates the exception:

    C#Runs
    var values = new List<int> { 1, 2 };
    try
    {
        foreach (int value in values)
        {
            Console.WriteLine($"Visited: {value}");
            values.Add(3);
        }
    }
    catch (InvalidOperationException)
    {
        Console.WriteLine("Next loop step threw InvalidOperationException.");
    }
    Output
    Visited: 1
    Next loop step threw InvalidOperationException.

    Since .NET Core 3.0, Dictionary.Remove and Clear do not invalidate active dictionary enumerators. Other dictionary changes can invalidate them. See the Dictionary.Remove remarks.

    The Dictionary documentation describes its contract and mutation exceptions.

    The mistake to avoid. Neither “all collections preserve insertion order” nor “every mutation breaks foreach” is a reliable rule. Check the specific contract.

    In an interview, say: “Dictionary enumeration order is not guaranteed. Adding, removing or replacing list items during foreach makes the next MoveNext—the method that advances the loop—throw InvalidOperationException. Dictionary Remove and Clear are exceptions since .NET Core 3.0. I remove list items backwards or collect changes first.”

    How do I prevent integer overflow in C# solutions?

    Overflow occurs when a result falls outside the numeric type's range. A long destination does not help if an earlier calculation already overflowed as int.

    C#Runs
    int a = int.MaxValue;
    int b = 2;
    long product = (long)a * b;
    long magnitude = Math.Abs((long)int.MinValue);
    Console.WriteLine($"Product: {product}");
    Console.WriteLine($"Magnitude: {magnitude}");
    
    try
    {
        int tooLarge = checked(a * b);
        Console.WriteLine(tooLarge);
    }
    catch (OverflowException)
    {
        Console.WriteLine("Checked multiplication overflowed.");
    }
    Output
    Product: 4294967294
    Magnitude: 2147483648
    Checked multiplication overflowed.

    Casting an operand widens the multiplication before it happens. The same principle applies to sums and differences: cast before the risky operation.

    checked makes overflowing integer arithmetic throw instead of silently wrapping. It does not increase the available range. Without an explicit context, nonconstant integer arithmetic follows the project's overflow-checking setting, normally unchecked.

    Math.Abs(int.MinValue) throws OverflowException: its positive magnitude cannot fit in int. Widening first makes that particular magnitude representable. Even long has limits, so establish bounds for the whole calculation. See checked and unchecked.

    The mistake to avoid. long result = a * b still multiplies two int operands as int. Widen an operand, not just the destination.

    In an interview, say: “I derive the result bounds, widen before arithmetic, and use checked when overflow should fail explicitly. Math.Abs(int.MinValue) throws, so I widen that value before taking its magnitude.”

    When should I use StringBuilder instead of concatenation?

    Strings are immutable: their characters cannot be changed after creation. Repeatedly appending to a growing string creates replacement strings and copies the existing prefix.

    For n fixed-size pieces, copying prefixes of sizes 1, 2, ..., n can require O(n²) total work and cumulative allocation.

    C#Runs
    using System.Text;
    
    string[] pieces = { "red", "green", "blue" };
    var builder = new StringBuilder();
    foreach (string piece in pieces)
        builder.Append(piece);
    
    string result = builder.ToString();
    Console.WriteLine(result);
    Console.WriteLine($"Final characters: {result.Length}");
    Output
    redgreenblue
    Final characters: 12

    StringBuilder maintains writable storage. ToString() still creates the final string.

    Cumulative allocated bytes count all allocations during an operation, including temporary objects later reclaimed. Live memory is the memory still retained at a particular point. Quadratic cumulative allocation does not mean quadratic live memory. Old prefixes that the program no longer uses can be freed by the garbage collector, which reclaims unused managed memory.

    A few fixed concatenations are usually clearer without a builder. When joining a known sequence with separators, consider string.Join. Microsoft's StringBuilder guidance explains why it is not an automatic replacement for every concatenation.

    The mistake to avoid. Do not repeatedly call builder.ToString() inside the append loop. That repeatedly copies the growing result again.

    In an interview, say: “Strings are immutable, so repeated growing concatenation can cause quadratic copying and cumulative allocation. I use StringBuilder for repeated appends, but it still allocates storage and the final string.”

    What is the difference between Substring and AsSpan?

    A span is a lightweight view over one unbroken block of memory, such as an array or the characters of a string. Span<T> permits writes; ReadOnlySpan<T> prevents writes through that view. A read-only view does not make a mutable underlying array immutable.

    A Substring call that returns part of the string—not empty and not the whole string—allocates a new string and copies those characters. Parsing a span instead avoids creating that temporary substring. In the measured example below, parsing with AsSpan allocates no managed bytes. Calling ToString() on a nonempty character span copies into a string.

    flowchart TD
        S["Input string"] -->|"Substring copies"| C["New string characters"]
        V["ReadOnlySpan view"] -->|"refers to a slice"| S

    The substring owns copied characters; the span view refers to characters in the input string.

    This example compares cumulative allocations on the current thread, not live memory or execution time. Input construction and warm-up calls are outside the measured regions. The byte counts may differ between runtimes.

    C#Runs
    string input = string.Concat(Enumerable.Repeat("12345,", 1000));
    _ = ParseSubstrings(input);
    _ = ParseSpans(input);
    
    long before = GC.GetAllocatedBytesForCurrentThread();
    int copiedSum = ParseSubstrings(input);
    long substringBytes = GC.GetAllocatedBytesForCurrentThread() - before;
    
    before = GC.GetAllocatedBytesForCurrentThread();
    int viewedSum = ParseSpans(input);
    long spanBytes = GC.GetAllocatedBytesForCurrentThread() - before;
    
    Console.WriteLine($"Sums: {copiedSum}, {viewedSum}");
    Console.WriteLine($"Substring allocated bytes: {substringBytes}");
    Console.WriteLine($"Span allocated bytes: {spanBytes}");
    
    static int ParseSubstrings(string text)
    {
        int sum = 0;
        int start = 0;
        while (start < text.Length)
        {
            int end = text.IndexOf(',', start);
            sum += int.Parse(text.Substring(start, end - start));
            start = end + 1;
        }
        return sum;
    }
    
    static int ParseSpans(string text)
    {
        int sum = 0;
        int start = 0;
        while (start < text.Length)
        {
            int end = text.IndexOf(',', start);
            sum += int.Parse(text.AsSpan(start, end - start));
            start = end + 1;
        }
        return sum;
    }
    Output
    Sums: 12345000, 12345000
    Substring allocated bytes: 32000
    Span allocated bytes: 0

    The first method creates one five-character substring per token. The second passes a view directly to int.Parse. These helpers assume valid numbers and a trailing comma; they are not general CSV parsers.

    Spans have restricted lifetimes: a view must not outlive its underlying storage. You cannot store a span in a class field. You also cannot keep using the same span after an await or a yield return in the same method. Use Memory<T> or ReadOnlyMemory<T> when you need a storable view across asynchronous work.

    stackalloc reserves temporary stack storage. Keep its size small and bounded, and avoid repeated stack allocations inside a loop. Do not assume that storage starts at zero:

    C#Runs
    Span<int> counts = stackalloc int[26];
    counts.Clear();
    foreach (char c in "banana")
        counts[c - 'a']++;
    Console.WriteLine($"a: {counts['a' - 'a']}");
    Output
    a: 3

    This example deliberately accepts only lowercase English letters. The fixed 26-counter bound makes the stack requirement independent of input length.

    Read the Span reference and memory and span usage guidelines for lifetime details.

    The mistake to avoid. A span avoids copying a slice; it does not make every operation using that slice allocation-free. A conversion back to a string reintroduces copying.

    In an interview, say: “Substring allocates a new string and copies characters when the result is neither empty nor the whole string. I can parse a span directly instead of creating that temporary string. Converting the view to a string copies, and spans have lifetime restrictions and cannot be class fields.”

    When does LINQ repeat work or allocate storage?

    Many LINQ operations describe a traversal rather than save its results. Enumerating the same deferred query twice can repeat filtering, parsing or other work.

    Materialization means executing a query and storing its results, for example with ToArray or ToList. That is useful when you deliberately want reusable results, but unnecessary when one traversal is enough.

    Predict the number of Testing lines:

    C#Runs
    int[] input = { 1, 2, 3, 4 };
    var matches = input.Where(x =>
    {
        Console.WriteLine($"Testing {x}");
        return x % 2 == 0;
    });
    
    Console.WriteLine($"Any: {matches.Any()}");
    Console.WriteLine($"Count: {matches.Count()}");
    
    int count = 0;
    long sum = 0;
    foreach (int value in input)
    {
        if (value % 2 != 0)
            continue;
        count++;
        sum += value;
    }
    Console.WriteLine($"One traversal: count={count}, sum={sum}");
    Output
    Testing 1
    Testing 2
    Any: True
    Testing 1
    Testing 2
    Testing 3
    Testing 4
    Count: 2
    One traversal: count=2, sum=6

    Any() stops after finding 2. Count() starts again and tests all four inputs. There are six Testing lines.

    The final loop calculates both required results in one traversal without storing the matches. If several later consumers need the actual matching values, materializing once can instead be the right trade-off.

    A collection's Count property does not traverse its elements. LINQ's Count() can use available count information for some sources, but may enumerate others. Explain your source and required traversals rather than memorizing runtime-specific shortcuts. For the cost of single LINQ calls, see Contains, Any and Count in LINQ and First, Last, ElementAt and Single in LINQ.

    The mistake to avoid. Neither “LINQ always allocates a list” nor “a query variable caches results” is true. Identify when execution happens and what is retained.

    In an interview, say: “Deferred LINQ queries can repeat work on each enumeration. I combine aggregates into one traversal, or deliberately buffer once when later consumers need reusable results.”

    Check yourself

    A solution processes n distinct integers. For each integer, it calls Contains on a growing List<int> before adding the integer. What is the total search cost?

    A O(n²)
    B O(1)
    C O(n)
    D O(n log n)
    Show answer

    Correct answer: A

    The searches inspect lists of sizes 0 through n - 1. Adding those costs gives O(n²), even though the code has one visible loop.

    You need to parse a slice of an existing string once and do not need to retain the slice. Which choice avoids creating a temporary substring?

    A int.Parse(text.Substring(start, length))
    B int.Parse(text.AsSpan(start, length).ToString())
    C int.Parse(text.AsSpan(start, length))
    D new StringBuilder(text.Substring(start, length)).ToString()
    Show answer

    Correct answer: C

    AsSpan supplies a read-only view that int.Parse can consume directly. The other choices create a string for the slice.

    Going deeper

    Collection complexity often treats key operations as constant-time. Hashing a string or comparing long common prefixes can depend on the number of characters examined. Include key length when it grows with the input.

    Keep fields that determine a key's equality, hash code or sorted position unchanged while the key is stored. Otherwise, later searches can follow rules that no longer match its stored position.

    The dictionary mutation exceptions do not make arbitrary updates safe, nor do they permit concurrent mutation without coordination.

    A priority queue does not guarantee first-in, first-out behavior among equal priorities. Include a sequence number in the priority when tie order matters. Continue with PriorityQueue patterns and API pitfalls.

    Version notes. PriorityQueue.Remove (a linear scan), Queue<T>.Capacity and Stack<T>.Capacity arrived in .NET 9, and PriorityQueue.Capacity in .NET 10. .NET 10 has no built-in deque type; see queues and deques in C#.

    For the next foundation, study arrays, strings and counting arrays.

    Sources

    Practice

    Practice test: Practice: The C# Angle: Collection Costs, LINQ Costs, Strings and Span in Coding Interviews7 questions · 1 mark each, no negative markingFull Access
    Take the test
    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 30 Nov 2026 ·