Skip to content
Search lessons, topics, tests…
Esc

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

    How to Solve and Check a Coding Problem in C#: Patterns, Tests and Measured Big-O

    Solve a C# coding interview problem by clarifying the rules, comparing approaches, testing the code and explaining its Big-O time and space costs.

    We will use duplicate detection to connect those steps. Then we will solve missing number, where a correct mathematical formula can still produce incorrect C# code.

    What should you clarify before coding?

    Interviewers commonly assess four areas: communication, problem solving, readable working code and testing. Exact scoring rubrics vary. Explain your choices as you work, rather than staying silent until the code is finished.

    Start by agreeing on the contract: what inputs the method accepts and what result it must produce.

    For “find duplicates,” ask:

    • Should I return a Boolean, one repeated value or every repeated value?
    • How many elements can there be? What values are allowed?
    • Can the array be empty or null?
    • Does “duplicate” mean the same value appears at least twice?
    • May I change the caller's array?

    Use a small example to settle ambiguity: “For [4, 1, 4], should I return true or return 4?”

    Then follow this spoken routine:

    flowchart TD
        A["Clarify the contract"] -->|guides| B["Try small examples"]
        B -->|then| C["Give a simple solution"]
        C -->|then| F["Improve it"]
        F -->|then| D["Write the code"]
        D -->|check with| E["Hand-test and explain costs"]

    The diagram shows the order of the discussion, not just the order of writing code.

    The brute-force solution below checks pairs of array elements. It gives you a useful starting point, even when it is too slow.

    For the examples below, our contract is: accept a non-null int[], return whether any value repeats, and allow every int value. Empty arrays return false. We will compare both mutation choices. Mutation means changing the supplied array itself.

    The mistake to avoid. Do not silently choose an interpretation. A fast method that returns the wrong kind of result still solves the wrong problem.

    In an interview, say: “Before choosing an approach, I would confirm the result, input size and value range, null and empty handling, duplicate rules and whether mutation is allowed. I would check my interpretation with a small example.”

    How does Big-O help you choose an approach?

    Time complexity describes how the work grows as the input grows. Here, n is the array length.

    For auxiliary space, compare what these methods keep besides the supplied array: the pair method has loop counters; the hash method also creates seen. We care about the peak: the largest amount needed at one time, not the total allocated across every step.

    These common bounds give you an initial shortlist:

    BoundPlain meaningA useful size clue
    O(1)Work does not grow with nOne comparison or indexed read
    O(log n)Growth follows how many times you can halve nRepeatedly narrowing a search range
    O(n)Work grows proportionally to nOften plausible for 100,000–1,000,000 items
    O(n log n)About n times that halving countSorting may be plausible at those sizes
    O(n²)Work grows with the square of nOften worth considering near 2,000 items
    O(2ⁿ)Each extra item can roughly double the workSome searches are plausible near 20 items

    These are rough interview estimates, not execution-time guarantees. As a rough budgeting assumption, allow 10⁸ simple operations per second: 2,000² is 4 million, and 1,000,000 × log₂(1,000,000) is about 20 million. But 100,000² is 10¹⁰, far beyond that one-second budget. At n = 20, 2ⁿ is about one million. But a million cheap comparisons differs greatly from a million operations that each copy an array.

    Input limits help you reject implausible approaches. They do not choose the algorithm for you.

    How can you detect duplicates in C# three ways?

    The brute-force approach compares each element with every later element. It avoids comparing an element with itself and avoids checking the same pair twice.

    Sorting removes repeated searching: once values are in order, equal values must be next to each other. However, Array.Sort rearranges the supplied array.

    A set stores unique values. A hash code is a number computed from a value by GetHashCode. A hash set uses that number to choose the small group of storage slots to search, rather than scanning all stored values. HashSet<T>.Add returns false when the value is already present, so one call can both check and insert.

    The program below runs the same cases through all three approaches. Predict which cases should return true, then the three array lines printed at the end.

    C#Runs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    var cases = new (string Name, int[] Values, bool Expected)[]
    {
        ("empty", Array.Empty<int>(), false),
        ("one item", new[] { 7 }, false),
        ("all distinct", new[] { 4, 1, 9 }, false),
        ("duplicate early", new[] { 4, 4, 1, 9 }, true),
        ("duplicate late", new[] { 4, 1, 9, 9 }, true),
        ("all equal", new[] { 5, 5, 5 }, true),
        ("negative duplicate", new[] { -3, 0, -3 }, true),
        ("distinct limits", new[] { int.MinValue, 0, int.MaxValue }, false),
        ("repeated limit", new[] { int.MaxValue, 0, int.MaxValue }, true)
    };
    
    foreach (var test in cases)
    {
        int[] original = (int[])test.Values.Clone();
        int[] sortable = (int[])test.Values.Clone();
    
        bool pairs = HasDuplicatePairs(test.Values);
        bool hashed = HasDuplicateHash(test.Values);
        bool sorted = HasDuplicateSort(sortable);
    
        bool passed = pairs == test.Expected
            && hashed == test.Expected
            && sorted == test.Expected
            && test.Values.SequenceEqual(original);
    
        Console.WriteLine($"{test.Name}: {(passed ? "PASS" : "FAIL")}");
    }
    
    int[] caller = { 3, 1, 2 };
    int[] copy = (int[])caller.Clone();
    HasDuplicateSort(copy);
    Console.WriteLine($"Sorted clone: {string.Join(", ", copy)}");
    Console.WriteLine($"Caller after sorting clone: {string.Join(", ", caller)}");
    HasDuplicateSort(caller);
    Console.WriteLine($"Caller after direct sort: {string.Join(", ", caller)}");
    
    static bool HasDuplicatePairs(int[] values)
    {
        ArgumentNullException.ThrowIfNull(values);
        for (int i = 0; i < values.Length; i++)
        {
            for (int j = i + 1; j < values.Length; j++)
            {
                if (values[i] == values[j])
                    return true;
            }
        }
        return false;
    }
    
    static bool HasDuplicateSort(int[] values)
    {
        ArgumentNullException.ThrowIfNull(values);
        Array.Sort(values);
        for (int i = 1; i < values.Length; i++)
        {
            if (values[i - 1] == values[i])
                return true;
        }
        return false;
    }
    
    static bool HasDuplicateHash(int[] values)
    {
        ArgumentNullException.ThrowIfNull(values);
        var seen = new HashSet<int>();
        foreach (int value in values)
        {
            if (!seen.Add(value))
                return true;
        }
        return false;
    }
    Output
    empty: PASS
    one item: PASS
    all distinct: PASS
    duplicate early: PASS
    duplicate late: PASS
    all equal: PASS
    negative duplicate: PASS
    distinct limits: PASS
    repeated limit: PASS
    Sorted clone: 1, 2, 3
    Caller after sorting clone: 3, 1, 2
    Caller after direct sort: 1, 2, 3

    What each approach saves

    The pair method spends time asking the same kind of membership question again and again: “Does this value occur later?”

    Sorting pays once to establish order. Its scan then checks only neighbors. Hashing instead remembers values already encountered.

    Expected time describes performance under the usual hashing assumptions. Worst-case time bounds the most expensive allowed execution. A collision occurs when different values map to the same hash bucket, the internal group searched for matching values. Many collisions can make a hash-set operation expensive.

    The call stack holds active method calls. Sorting can need stack memory for nested calls, even though it rearranges the original array. An in-place algorithm rearranges the data inside the array it was given instead of building a new array. Here, “in-place” does not mean “uses no extra memory.”

    ApproachTimePeak auxiliary spaceChanges the supplied array?
    Pair checksWorst O(n²)O(1)No
    Hash setExpected O(n); worst O(n²) with many collisionsO(n)No
    Sort, then scanO(n log n)O(log n) sorting stackYes
    Clone, sort, then scanO(n log n)O(n) including the cloneNo

    Cloning also takes O(n) copying time. It does not change the overall sorting bound because n log n is the dominant term: the part that eventually grows faster.

    What the shared tests check

    Negatives and integer limits check that the code compares values directly rather than relying on unsafe arithmetic shortcuts. The final example proves the mutation distinction: sorting the clone preserves the caller's order; sorting the caller directly produces 1, 2, 3.

    All three methods reject null with ArgumentNullException. In a real interview, also test the maximum permitted size. Choose a distinct array to prevent an early duplicate from hiding the full workload.

    The mistake to avoid. Do not call sorting a constant-space, non-mutating alternative without qualification. Direct Array.Sort changes the caller's array and uses stack space; cloning preserves the input but adds linear memory.

    In an interview, say: “Pair checks take quadratic time and constant extra space. Sorting takes O(n log n) time and changes the array unless I clone it. A hash set uses linear extra space for expected linear time. I would choose after confirming mutation and memory limits.”

    How do you derive time and space complexity from code?

    Count the total work, including work inside called methods. A single visible loop is not enough evidence for O(n).

    For the pair method on distinct input, the inner loop performs:

    (n - 1) + (n - 2) + ... + 1 = n(n - 1) / 2

    That is (n² - n) / 2. Keeping the dominant term gives O(n²).

    This small program counts pair comparisons for two distinct arrays. Predict whether doubling the length doubles or roughly quadruples the count.

    C#Runs
    using System;
    
    foreach (int n in new[] { 100, 200 })
    {
        int[] values = new int[n];
        for (int i = 0; i < n; i++)
            values[i] = i;
    
        long comparisons = 0;
        for (int i = 0; i < values.Length; i++)
        {
            for (int j = i + 1; j < values.Length; j++)
            {
                comparisons++;
                if (values[i] == values[j])
                    throw new InvalidOperationException("Expected distinct input.");
            }
        }
        Console.WriteLine($"n={n}: {comparisons} pair comparisons");
    }
    Output
    n=100: 4950 pair comparisons
    n=200: 19900 pair comparisons

    The count grows a little more than four times. This agrees with the quadratic derivation. Two measurements do not prove a bound.

    Now include hidden work. Array.Sort uses introsort, which switches to heapsort when quicksort goes too deep, so it costs O(n log n) even in the worst case. The scan adds O(n). HashSet.Add may grow its internal storage. The documentation gives O(1) for a normal non-resizing insertion and O(n) when resizing is necessary. Across a sequence of insertions, occasional resizing can be spread over many cheap operations; this is amortized analysis. With normal hashing assumptions, the full duplicate scan is expected O(n).

    Early exits need separate treatment. The pair and hash methods can return after discovering a duplicate near the start. The sorting method still sorts before its scan can return.

    The mistake to avoid. Counting one insertion attempt per element does not count hashing, collision searches or resizing. Likewise, one timed run cannot establish a complexity bound.

    In an interview, say: “Here n is the array length. I count total work, including called methods, then keep the dominant term. I report peak auxiliary storage and distinguish expected from worst-case time. Doubling measurements are a sanity check, not a proof.”

    For more hidden library work, continue with C# collection, LINQ, string and Span costs.

    How do you prove the duplicate solution is correct?

    For this hash-set solution, the invariant is the following statement about seen before each element:

    Before processing each element, seen contains exactly the distinct values from the earlier elements.

    Try the tricky case [3, 1, 3]. The matching values are not adjacent, so checking only neighboring values in the original array would fail.

    C#Runs
    using System;
    using System.Collections.Generic;
    
    int[] values = { 3, 1, 3 };
    var seen = new HashSet<int>();
    bool duplicate = false;
    
    foreach (int value in values)
    {
        bool added = seen.Add(value);
        Console.WriteLine($"value={value}; added={added}; stored={seen.Count}");
        if (!added)
        {
            duplicate = true;
            break;
        }
    }
    Console.WriteLine($"Duplicate: {duplicate}");
    Output
    value=3; added=True; stored=1
    value=1; added=True; stored=2
    value=3; added=False; stored=2
    Duplicate: True

    A correctness argument has three parts:

    1. Initialization: Before the first element, there are no earlier elements. The empty set is correct.
    2. Preservation: If the current value is absent, adding it makes the set correct for the next iteration. If it is present, an earlier equal value exists, so returning true is correct.
    3. Termination: If the loop finishes, every value was new when encountered. Therefore no duplicate exists, and returning false is correct.

    The shared tests above exercise normal cases, boundaries and deliberately troublesome inputs. Such adversarial tests target likely mistakes, such as assuming duplicates must be adjacent. They help expose bugs but cannot cover every allowed input.

    The mistake to avoid. Do not present “all my tests passed” as a proof. Tests inspect selected inputs; the invariant explains why every input satisfying the contract is handled correctly.

    In an interview, say: “Before each iteration, the set contains exactly the earlier values. It starts empty, and each successful insertion preserves that statement. A failed insertion proves a duplicate; reaching the end proves there is none. I would also test empty, one-item, all-distinct, early and late duplicates, all-equal, negative and extreme values where allowed.”

    How do you find a missing number without int overflow?

    Now change the contract: the array has length n and contains distinct values from 0 through n, with exactly one missing. The values need not be sorted.

    The complete range sums to n(n + 1) / 2. Subtracting every supplied value leaves the missing one.

    An alternative uses XOR (^): equal numbers cancel, so combining every number from 0 through n with every supplied value leaves the missing number without arithmetic overflow.

    Integer overflow occurs when an arithmetic result does not fit the integer type used to calculate it. Assigning the result to long afterward is too late if the multiplication already overflowed as int. See C# arithmetic operators for how operand types determine the calculation's type.

    Widen before both the addition and multiplication: (long)n * (n + 1L) / 2.

    Predict the missing numbers below, including the result for an empty array.

    C#Runs
    using System;
    
    Console.WriteLine($"Missing from [3, 0, 1]: {MissingNumber(new[] { 3, 0, 1 })}");
    Console.WriteLine($"Missing from []: {MissingNumber(Array.Empty<int>())}");
    Console.WriteLine($"Missing from [1]: {MissingNumber(new[] { 1 })}");
    Console.WriteLine($"Missing from [0]: {MissingNumber(new[] { 0 })}");
    
    int n = 100_000;
    int[] large = new int[n];
    for (int i = 0; i < n; i++)
        large[i] = i;
    Console.WriteLine($"Missing from large input: {MissingNumber(large)}");
    
    try
    {
        int unsafeSum = checked(n * (n + 1) / 2);
        Console.WriteLine(unsafeSum);
    }
    catch (OverflowException)
    {
        Console.WriteLine("int formula overflow detected");
    }
    long assignedAfterward = unchecked(n * (n + 1) / 2);
    Console.WriteLine($"Unchecked int sum assigned to long: {assignedAfterward}");
    Console.WriteLine($"Widened range sum: {(long)n * (n + 1L) / 2}");
    
    static int MissingNumber(int[] values)
    {
        ArgumentNullException.ThrowIfNull(values);
        int n = values.Length;
        long remaining = (long)n * (n + 1L) / 2;
        foreach (int value in values)
            remaining -= value;
        return (int)remaining;
    }
    Output
    Missing from [3, 0, 1]: 2
    Missing from []: 0
    Missing from [1]: 0
    Missing from [0]: 1
    Missing from large input: 100000
    int formula overflow detected
    Unchecked int sum assigned to long: 705082704
    Widened range sum: 5000050000

    For [3, 0, 1], the full range sum is 6. Subtracting 3, 0 and 1 leaves 2. For an empty array, the complete range contains only 0, so the answer is 0.

    The invariant is that remaining equals the complete range sum minus the values processed so far. At termination, only the missing value remains.

    The method assumes the promised distinctness and range; it does not validate them.

    The checked keyword detects this overflow by throwing; it does not make the calculation wider. Without it, C# lets non-constant int arithmetic wrap silently; see preventing integer overflow in C#.

    See the integer type limits when choosing arithmetic types.

    The mistake to avoid. Do not rely on a long destination to protect an int expression. Widen an operand before the risky arithmetic happens.

    In an interview, say: “Yes, the missing-number sum can overflow int before division or assignment. I use (long)n * (n + 1L) / 2, then subtract into a long. checked detects overflow; it does not prevent it.”

    Which coding pattern clues should you recognize?

    A coding pattern is a reusable way to organize work. Look for a reason the pattern fits, not just a familiar word in the question.

    • Repeated membership checks: Hashing can remember what has already appeared. Study hashing patterns and bad hash codes.
    • Sorted input: Two pointers use two positions that move according to comparisons; each move needs a reason it cannot skip an answer. Continue with two pointers.
    • Contiguous ranges: These contain consecutive elements with no gaps. Before choosing a sliding window, ask whether you can update the needed information and justify the boundary movements. Continue with sliding-window patterns.
    • Levels or minimum steps in an unweighted graph: A graph represents items connected by links; unweighted links each count as one step. Breadth-first search (BFS) visits items level by level, so it reaches each item first by the fewest steps. Continue with graphs with BFS and DFS.
    • Top-k requests: These ask for the k largest, smallest or highest-priority items. A heap keeps its highest-priority item readily available without fully sorting everything. Compare its cost with sorting in heaps and PriorityQueue.

    The mistake to avoid. A clue suggests an approach to investigate. It does not establish correctness or override input constraints.

    In an interview, say: “I look for repeated work and a structure that removes it. Then I justify why its operations preserve the answer and compare its time, memory and mutation costs.”

    Check yourself

    You must detect duplicates without changing the caller's array. Which statement is correct?

    A Array.Sort works on an internal copy, so the caller's array is unchanged.
    B HashSet.Add runs in constant time on every call, even when it resizes.
    C Sorting a clone protects the caller's array but adds O(n) copy time and space.
    D An early return on the first match makes nested pair checks O(n) worst case.
    Show answer

    Correct answer: C

    The clone is a separate array. Sorting it preserves the caller's order, but creating and retaining it costs time and memory.

    Why is assigning n * (n + 1) / 2 to a long not enough to avoid int overflow?

    A Division always converts the result back to int.
    B long cannot hold a larger integer than int.
    C checked automatically changes multiplication to long arithmetic.
    D The expression can overflow as int before assignment to long.
    Show answer

    Correct answer: D

    The operand types determine the arithmetic. Widen before the addition and multiplication, as in (long)n * (n + 1L) / 2. checked detects overflow rather than widening the expression.

    Going deeper

    The cost of equality and hashing also matters. Our examples use integers. For other keys, computing a hash or comparing two values may itself depend on the key's size. The HashSet implementation shows the collision-search work that an insertion-attempt counter misses.

    For sorting, the runtime sorting implementation provides the detail behind the logarithmic stack allowance. Keep implementation details separate from the contract you need: whether the array changes, what costs you rely on, and what assumptions make those costs valid.

    Sources

    Practice

    Practice test: Practice: How to Solve and Check a Coding Problem in C#: Patterns, Tests and Measured Big-O8 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 ·