Autocoder

C# Coding Interview Questions

Last updated 2026-11-19

A C# coding round is judged on correct, readable code in modern idiom: Dictionary and HashSet for lookup, Span and StringBuilder where they matter, LINQ when it is clearer and a plain loop when it is faster. Interviewers also notice null handling and overflow.

Each solution compiles on .NET 8 with C# 12 and states its complexity. For round strategy, see how to crack a DSA coding round and the topic pages in the DSA hub.

Language versionC# 12 on .NET 8
Problems15, easy to medium
FocusCorrectness, then complexity, then style

C# idioms that signal fluency

C# Coding Interview Questions: questions with worked answers

  1. 1

    Two Sum: return indices of two numbers adding to a target.

    easy

    Store each value and its index in a dictionary and look up target minus the current value. Check before inserting so an element cannot pair with itself. O(n) time and O(n) space, against O(n squared) for nested loops.

    csharp
    static int[] TwoSum(int[] nums, int target) {
        var seen = new Dictionary<int, int>();
        for (int i = 0; i < nums.Length; i++) {
            if (seen.TryGetValue(target - nums[i], out int j)) return [j, i];
            seen[nums[i]] = i;
        }
        return [];
    }
    // TwoSum([2,7,11,15], 9) -> [0, 1]
  2. 2

    Valid parentheses.

    easy

    Push the expected closing bracket for each opener on a stack; on a closer it must match the popped value. The string is valid only if the stack ends empty. O(n) time and O(n) space.

    csharp
    static bool IsValid(string s) {
        var st = new Stack<char>();
        foreach (char ch in s) {
            switch (ch) {
                case '(': st.Push(')'); break;
                case '[': st.Push(']'); break;
                case '{': st.Push('}'); break;
                default:
                    if (st.Count == 0 || st.Pop() != ch) return false;
                    break;
            }
        }
        return st.Count == 0;
    }
  3. 3

    Check whether two strings are anagrams.

    easy

    Compare lengths, then count letters up for one string and down for the other; any non-zero count means no. For lowercase a to z a 26-element array gives O(n) time and O(1) space, and a Dictionary<char,int> handles arbitrary characters.

    csharp
    static bool IsAnagram(string a, string b) {
        if (a.Length != b.Length) return false;
        Span<int> cnt = stackalloc int[26];
        for (int i = 0; i < a.Length; i++) { cnt[a[i] - 'a']++; cnt[b[i] - 'a']--; }
        foreach (int c in cnt) if (c != 0) return false;
        return true;
    }
  4. 4

    Character frequency and first non-repeating character.

    easy

    Count with a dictionary, then scan the original string to find the first character with count 1, preserving order. Two passes, O(n) time and O(k) space for k distinct characters.

    csharp
    static char? FirstUnique(string s) {
        var cnt = new Dictionary<char, int>();
        foreach (char ch in s) cnt[ch] = cnt.GetValueOrDefault(ch) + 1;
        foreach (char ch in s) if (cnt[ch] == 1) return ch;
        return null;
    }
    // FirstUnique("swiss") -> 'w'
  5. 5

    Fibonacci: recursion, iteration and overflow.

    easy

    Naive recursion is O(2^n). Iteration is O(n) time and O(1) space. long holds up to fib(92); fib(93) overflows long but still fits in ulong, and beyond that use System.Numerics.BigInteger. Use a checked context to fail loudly instead of wrapping silently.

    csharp
    static long Fib(int n) {
        long a = 0, b = 1;
        for (int i = 0; i < n; i++) { checked { (a, b) = (b, a + b); } }
        return a;
    }
    // Fib(10) = 55; Fib(92) = 7540113804746346429
  6. 6

    Generate primes up to n.

    easy

    The Sieve of Eratosthenes marks multiples of each prime starting at its square. O(n log log n) time and O(n) space. Use long for the starting product i * i to avoid overflow for large n.

    csharp
    static List<int> Primes(int n) {
        var composite = new bool[n + 1];
        var primes = new List<int>();
        for (int i = 2; i <= n; i++) {
            if (composite[i]) continue;
            primes.Add(i);
            for (long j = (long)i * i; j <= n; j += i) composite[(int)j] = true;
        }
        return primes;
    }
  7. 7

    Maximum subarray sum (Kadane).

    medium

    Track the best sum ending at the current element by either extending or restarting, and keep the global best. O(n) time and O(1) space, correct even if all numbers are negative because it starts from the first element.

    csharp
    static int MaxSubArray(int[] a) {
        int best = a[0], cur = a[0];
        for (int i = 1; i < a.Length; i++) {
            cur = Math.Max(a[i], cur + a[i]);
            best = Math.Max(best, cur);
        }
        return best;
    }
  8. 8

    Binary search, and what Array.BinarySearch returns.

    medium

    Keep a half-open or closed range and compute the midpoint as lo + (hi - lo) / 2 to avoid overflow. O(log n) on sorted data. The built-in Array.BinarySearch returns the index if found, otherwise the bitwise complement (~) of the index where the value would be inserted, so a negative result tells you the insert position.

    csharp
    static int Search(int[] a, int key) {
        int lo = 0, hi = a.Length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == key) return mid;
            if (a[mid] < key) lo = mid + 1; else hi = mid - 1;
        }
        return ~lo;      // insertion point, like Array.BinarySearch
    }
  9. 9

    Longest substring without repeating characters.

    medium

    Use a sliding window with a dictionary of each character's last index. When a repeated character lies inside the window, move the start past its previous position. O(n) time, O(k) space.

    csharp
    static int LongestUnique(string s) {
        var last = new Dictionary<char, int>();
        int best = 0, start = 0;
        for (int i = 0; i < s.Length; i++) {
            if (last.TryGetValue(s[i], out int j) && j >= start) start = j + 1;
            last[s[i]] = i;
            best = Math.Max(best, i - start + 1);
        }
        return best;
    }
    // LongestUnique("abcabcbb") -> 3
  10. 10

    Merge overlapping intervals.

    medium

    Sort by start, then walk through, extending the last merged interval when the next start is not greater than its end. O(n log n) for the sort, O(n) extra space. Copy the arrays if the input must not be mutated.

    csharp
    static List<int[]> Merge(int[][] intervals) {
        var res = new List<int[]>();
        foreach (var x in intervals.OrderBy(a => a[0])) {
            if (res.Count > 0 && x[0] <= res[^1][1]) res[^1][1] = Math.Max(res[^1][1], x[1]);
            else res.Add([x[0], x[1]]);
        }
        return res;
    }
    // [[1,3],[2,6],[8,10]] -> [[1,6],[8,10]]
  11. 11

    Group words that are anagrams of each other.

    medium

    Use the sorted letters of each word as a canonical key and group by it. With words of length k the sort costs O(k log k) per word, so O(n k log k) overall; a 26-count signature key gives O(n k).

    csharp
    static List<List<string>> GroupAnagrams(string[] words) =>
        words.GroupBy(w => new string(w.OrderBy(c => c).ToArray()))
             .Select(g => g.ToList()).ToList();
    // ["eat","tea","tan","ate","nat","bat"] -> [[eat,tea,ate],[tan,nat],[bat]]
  12. 12

    Remove duplicates from a list, preserving order.

    medium

    HashSet.Add returns false for a repeated item, so one pass keeps the first occurrence. O(n) time and O(n) space. Enumerable.Distinct does the same in LINQ and also preserves first-seen order in practice.

    csharp
    static List<T> Dedupe<T>(IEnumerable<T> src) {
        var seen = new HashSet<T>();
        var res = new List<T>();
        foreach (var x in src) if (seen.Add(x)) res.Add(x);
        return res;
    }
  13. 13

    Implement an LRU cache with O(1) get and put.

    hard

    Combine a dictionary from key to linked-list node with a LinkedList ordered by recency. On access move the node to the front; when capacity is exceeded, remove the last node and its dictionary entry. Both structures are O(1) per operation. Not thread safe; add a lock for concurrent use.

    csharp
    public class LruCache<K, V> where K : notnull {
        private readonly int _cap;
        private readonly Dictionary<K, LinkedListNode<(K Key, V Val)>> _map = new();
        private readonly LinkedList<(K Key, V Val)> _list = new();
        public LruCache(int cap) => _cap = cap;
        public bool TryGet(K key, out V val) {
            if (_map.TryGetValue(key, out var n)) {
                _list.Remove(n); _list.AddFirst(n); val = n.Value.Val; return true;
            }
            val = default!; return false;
        }
        public void Put(K key, V val) {
            if (_map.TryGetValue(key, out var n)) _list.Remove(n);
            else if (_map.Count == _cap) { _map.Remove(_list.Last!.Value.Key); _list.RemoveLast(); }
            _map[key] = _list.AddFirst((key, val));
        }
    }
  14. 14

    Reverse a singly linked list.

    medium

    Iterate once while reversing the next pointers, tracking the previous node. O(n) time and O(1) space. The recursive form is elegant but uses O(n) stack.

    csharp
    class Node { public int Val; public Node? Next; }
    static Node? Reverse(Node? head) {
        Node? prev = null;
        while (head != null) {
            var next = head.Next;
            head.Next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }
  15. 15

    Write a thread-safe singleton in C#.

    medium

    Lazy<T> is thread safe by default (ExecutionAndPublication mode) and is the simplest correct form. A static readonly field initialised inline also works, since the CLR guarantees type initialisation runs once. Avoid hand-written double-checked locking unless you can explain the memory model. Prefer dependency injection with AddSingleton in real applications.

    csharp
    public sealed class Config {
        private static readonly Lazy<Config> _instance = new(() => new Config());
        private Config() { }
        public static Config Instance => _instance.Value;
    }

Frequently asked questions

Which C# features help in coding rounds?

Tuples, local functions, index and range syntax, collection expressions, pattern matching and switch expressions make solutions short and clear.

Should I use LINQ in coding interviews?

Yes where it is clearer, but state the complexity: OrderBy is O(n log n), and chained LINQ allocates.

How do I read input fast in C#?

Use Console.ReadLine with string.Split and int.Parse; for very large inputs use a buffered stream reader.

Where can I practise topic by topic?

The DSA hub lists arrays, strings, trees, heaps and more.

Related guides

More in Programming Language Interview Questions by Language

See all in this section