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 version | C# 12 on .NET 8 |
|---|---|
| Problems | 15, easy to medium |
| Focus | Correctness, then complexity, then style |
C# idioms that signal fluency
- Dictionary.TryGetValue and TryAdd instead of ContainsKey plus indexer.
- HashSet.Add returning false for duplicates.
- Tuples and deconstruction for swaps and multiple returns: (a, b) = (b, a).
- Index and range syntax: arr[^1] for the last element, arr[1..3] for slices.
- StringBuilder for building text in loops, string.Join for collections.
C# Coding Interview Questions: questions with worked answers
1 Two Sum: return indices of two numbers adding to a target.
easyStore 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.
csharpstatic 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 Valid parentheses.
easyPush 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.
csharpstatic 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 Check whether two strings are anagrams.
easyCompare 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.
csharpstatic 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 Character frequency and first non-repeating character.
easyCount 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.
csharpstatic 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 Fibonacci: recursion, iteration and overflow.
easyNaive 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.
csharpstatic 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) = 75401138047463464296 Generate primes up to n.
easyThe 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.
csharpstatic 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 Maximum subarray sum (Kadane).
mediumTrack 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.
csharpstatic 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 Binary search, and what Array.BinarySearch returns.
mediumKeep 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.
csharpstatic 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 Longest substring without repeating characters.
mediumUse 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.
csharpstatic 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") -> 310 Merge overlapping intervals.
mediumSort 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.
csharpstatic 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 Group words that are anagrams of each other.
mediumUse 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).
csharpstatic 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 Remove duplicates from a list, preserving order.
mediumHashSet.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.
csharpstatic 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 Implement an LRU cache with O(1) get and put.
hardCombine 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.
csharppublic 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 Reverse a singly linked list.
mediumIterate 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.
csharpclass 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 Write a thread-safe singleton in C#.
mediumLazy<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.
csharppublic 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
- C# Collections Interview Questions
- C# Delegates and Events Interview Questions
- C# Interview Questions and Answers
- C# LINQ Interview Questions
- C# OOPs Interview Questions
- C++ Coding Interview Questions
- C++ Interview Questions and Answers
- C++ Memory Management Interview Questions
- C++ OOPS Interview Questions
- C++ Pointers and References Interview Questions
- C++ Smart Pointers Interview Questions
- C++ STL Interview Questions