30 C# Coding Interview Problems for Freshers
Codevity Admin · 10/25/2026
Codevity Admin · 10/25/2026
Most fresher coding rounds draw from the same small set of problems. For each one below you get the idea, the complexity, and working C# code that was compiled and run. Type each solution yourself before you read the next, then test it with an empty input, a single item and a duplicate.
Before you code, always say three things aloud: what the input and output are, what the edge cases are (null, empty, one item, duplicates, negative numbers), and what complexity you are aiming for.
| # | Problem | Idea | Time |
|---|---|---|---|
| 1 | Reverse a string | Swap characters from both ends of a char[] | O(n) |
| 2 | Palindrome (ignore case and punctuation) | Compare from both ends, skipping non-alphanumeric characters | O(n) |
| 11 | Character frequency | Dictionary<char, int> | O(n) |
| 12 | First non-repeating character | Count first, then scan in order | O(n) |
| 13 | Anagram check | Compare character counts | O(n) |
| 18 | Longest word in a sentence | Split on non-letters and keep the longest | O(n) |
| 19 and 28 | Word frequency, as a sorted table | Split, lower-case, count in a dictionary, then order by count | O(n) plus sorting |
| 29 | Remove duplicate characters, keep order | HashSet<char> of what you have already seen | O(n) |
Console.WriteLine(Reverse("interview")); // weivretni
Console.WriteLine(IsPalindrome("A man, a plan, a canal: Panama")); // True
Console.WriteLine(FirstNonRepeating("swiss")); // w
Console.WriteLine(IsAnagram("listen", "silent")); // True
Console.WriteLine(LongestWord("Hello, wonderful world!")); // wonderful
Console.WriteLine(RemoveDuplicateChars("programming")); // progamin
foreach (var pair in WordFrequency("the cat and the hat and the bat"))
Console.WriteLine($"{pair.Key}: {pair.Value}");
static string Reverse(string text)
{
char[] chars = text.ToCharArray();
for (int left = 0, right = chars.Length - 1; left < right; left++, right--)
(chars[left], chars[right]) = (chars[right], chars[left]);
return new string(chars);
}
static bool IsPalindrome(string text)
{
int left = 0, right = text.Length - 1;
while (left < right)
{
if (!char.IsLetterOrDigit(text[left])) { left++; continue; }
if (!char.IsLetterOrDigit(text[right])) { right--; continue; }
if (char.ToLowerInvariant(text[left]) != char.ToLowerInvariant(text[right])) return false;
left++;
right--;
}
return true;
}
static char? FirstNonRepeating(string text)
{
var counts = new Dictionary<char, int>();
foreach (char c in text) counts[c] = counts.GetValueOrDefault(c) + 1;
foreach (char c in text) if (counts[c] == 1) return c;
return null;
}
static bool IsAnagram(string a, string b)
{
if (a.Length != b.Length) return false;
var counts = new Dictionary<char, int>();
foreach (char c in a) counts[c] = counts.GetValueOrDefault(c) + 1;
foreach (char c in b)
{
if (!counts.TryGetValue(c, out int n) || n == 0) return false;
counts[c] = n - 1;
}
return true;
}
static string LongestWord(string sentence)
{
string longest = "";
foreach (string word in sentence.Split(new[] { ' ', ',', '.', '!', '?' }, StringSplitOptions.RemoveEmptyEntries))
if (word.Length > longest.Length) longest = word;
return longest;
}
static string RemoveDuplicateChars(string text)
{
var seen = new HashSet<char>();
var result = new System.Text.StringBuilder();
foreach (char c in text)
if (seen.Add(c)) result.Append(c);
return result.ToString();
}
static IEnumerable<KeyValuePair<string, int>> WordFrequency(string text)
{
var counts = new Dictionary<string, int>();
foreach (string word in text.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries))
counts[word] = counts.GetValueOrDefault(word) + 1;
return counts.OrderByDescending(p => p.Value).ThenBy(p => p.Key);
}Standalone versions: reverse and palindrome and character frequency.
| # | Problem | Idea | Time |
|---|---|---|---|
| 3 | Reverse an integer, detect 32-bit overflow | Pop digits with % 10, build with checked arithmetic | O(digits) |
| 4 | Factorial | Loop (or recursion) with checked to catch overflow, reject negatives | O(n) |
| 5 | Fibonacci | Keep only the last two values | O(n) time, O(1) space |
| 6 | Prime test | Try divisors up to the square root of n | O(sqrt n) |
| 7 | Armstrong number | Sum of each digit raised to the number of digits | O(digits) |
| 8 | Swap two values without a temp variable | Tuple swap, or XOR | O(1) |
Notes worth saying aloud: the XOR swap does not work if both names refer to the same variable, and the tuple swap is the readable choice. Factorial overflows a above 20, which is why matters.
| # | Problem | Idea | Time |
|---|---|---|---|
| 9 | Largest and second largest in one pass | Track two variables while scanning | O(n) |
| 10 | Remove duplicates without | of seen values | O(n) |
| 14 | Missing number from 1 to N | Expected sum minus actual sum | O(n) |
| 15 | Find all duplicates | returns false for a repeat | O(n) |
| 16 | Two sum | Dictionary of value to index, look up the complement | O(n) |
| 17 | Sort without library sort | Bubble sort (stop early if no swaps) | O(n squared) |
| 21 | Intersection of two arrays | Put one in a , scan the other | O(n + m) |
| 22 | Merge two sorted arrays | Two pointers, always take the smaller | O(n + m) |
See also the standalone two sum snippet. For "missing number", mention that the sum formula can overflow for a huge , and that XOR is an overflow-free alternative.
| # | Problem | Idea | Time |
|---|---|---|---|
| 20 | Balanced parentheses | Push openers on a , pop and match on closers | O(n) |
| 23 | Stack from scratch | Array plus a field; grow when full | O(1) per operation |
| 24 | Queue from scratch | Circular array with head and tail indexes | O(1) per operation |
| 30 | In-memory cache with expiry | Dictionary of value plus expiry time, for thread safety | O(1) average |
Standalone: balanced parentheses. For production caching, mention (), which also handles eviction and size limits.
| # | Problem | Idea |
|---|---|---|
| 25 | Sort employees by department, then salary descending | then |
| 26 | Total inventory value per product category | then |
| 27 | Second highest distinct salary | , , , , |
Standalone: group and total with LINQ and second highest salary with LINQ.
(a, b) = (b, a)longcheckedDistinct()HashSet<int>HashSet.AddHashSetNStack<char>countlockMemoryCacheMicrosoft.Extensions.Caching.MemoryOrderByThenByDescendingGroupBySumSelectDistinctOrderByDescendingSkip(1)FirstOrDefaultConsole.WriteLine(ReverseInt(123)); // 321
Console.WriteLine(ReverseInt(1534236469)); // 0 (the reverse does not fit in an int)
Console.WriteLine(Factorial(5)); // 120
Console.WriteLine(string.Join(", ", Fibonacci(8))); // 0, 1, 1, 2, 3, 5, 8, 13
Console.WriteLine(IsPrime(97)); // True
Console.WriteLine(IsPrime(91)); // False
Console.WriteLine(IsArmstrong(153)); // True
Console.WriteLine(IsArmstrong(154)); // False
int x = 5, y = 9;
x ^= y; y ^= x; x ^= y; // XOR swap
Console.WriteLine($"{x} {y}"); // 9 5
static int ReverseInt(int number)
{
int result = 0;
while (number != 0)
{
int digit = number % 10;
number /= 10;
try { result = checked(result * 10 + digit); }
catch (OverflowException) { return 0; }
}
return result;
}
static long Factorial(int n)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), "n must not be negative.");
long result = 1;
for (int i = 2; i <= n; i++) result = checked(result * i);
return result;
}
static IEnumerable<long> Fibonacci(int count)
{
long previous = 0, current = 1;
for (int i = 0; i < count; i++)
{
yield return previous;
(previous, current) = (current, previous + current);
}
}
static bool IsPrime(int n)
{
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
for (int d = 3; (long)d * d <= n; d += 2)
if (n % d == 0) return false;
return true;
}
static bool IsArmstrong(int n)
{
int digits = n.ToString().Length, sum = 0;
for (int rest = n; rest > 0; rest /= 10)
sum += (int)Math.Pow(rest % 10, digits);
return sum == n;
}var (largest, second) = TwoLargest(new[] { 4, 9, 2, 9, 7 });
Console.WriteLine($"{largest}, {second}"); // 9, 7
Console.WriteLine(string.Join(", ", RemoveDuplicates(new[] { 3, 1, 3, 2, 1 }))); // 3, 1, 2
Console.WriteLine(MissingNumber(new[] { 1, 2, 4, 5 }, 5)); // 3
Console.WriteLine(string.Join(", ", FindDuplicates(new[] { 1, 2, 3, 2, 1, 4 }))); // 2, 1
Console.WriteLine(string.Join(", ", TwoSum(new[] { 2, 7, 11, 15 }, 9))); // 0, 1
Console.WriteLine(string.Join(", ", BubbleSort(new[] { 5, 2, 9, 1 }))); // 1, 2, 5, 9
Console.WriteLine(string.Join(", ", Intersection(new[] { 1, 2, 2, 3 }, new[] { 2, 3, 4 }))); // 2, 3
Console.WriteLine(string.Join(", ", MergeSorted(new[] { 1, 4, 7 }, new[] { 2, 3, 9 }))); // 1, 2, 3, 4, 7, 9
static (int Largest, int Second) TwoLargest(int[] values)
{
int largest = int.MinValue, second = int.MinValue;
foreach (int v in values)
{
if (v > largest) { second = largest; largest = v; }
else if (v > second && v < largest) second = v; // distinct values only
}
return (largest, second);
}
static int[] RemoveDuplicates(int[] values)
{
var seen = new HashSet<int>();
var result = new List<int>();
foreach (int v in values)
if (seen.Add(v)) result.Add(v);
return result.ToArray();
}
static int MissingNumber(int[] values, int n)
{
int expected = n * (n + 1) / 2;
return expected - values.Sum();
}
static int[] FindDuplicates(int[] values)
{
var seen = new HashSet<int>();
var duplicates = new List<int>();
foreach (int v in values)
if (!seen.Add(v) && !duplicates.Contains(v)) duplicates.Add(v);
return duplicates.ToArray();
}
static int[] TwoSum(int[] values, int target)
{
var indexByValue = new Dictionary<int, int>();
for (int i = 0; i < values.Length; i++)
{
if (indexByValue.TryGetValue(target - values[i], out int j)) return new[] { j, i };
indexByValue[values[i]] = i;
}
return Array.Empty<int>();
}
static int[] BubbleSort(int[] values)
{
int[] a = (int[])values.Clone();
for (int pass = 0; pass < a.Length - 1; pass++)
{
bool swapped = false;
for (int i = 0; i < a.Length - 1 - pass; i++)
{
if (a[i] > a[i + 1]) { (a[i], a[i + 1]) = (a[i + 1], a[i]); swapped = true; }
}
if (!swapped) break;
}
return a;
}
static int[] Intersection(int[] first, int[] second)
{
var set = new HashSet<int>(first);
var result = new List<int>();
foreach (int v in second)
if (set.Remove(v)) result.Add(v); // Remove returns true once per distinct value
return result.ToArray();
}
static int[] MergeSorted(int[] a, int[] b)
{
var result = new int[a.Length + b.Length];
int i = 0, j = 0, k = 0;
while (i < a.Length && j < b.Length) result[k++] = a[i] <= b[j] ? a[i++] : b[j++];
while (i < a.Length) result[k++] = a[i++];
while (j < b.Length) result[k++] = b[j++];
return result;
}Console.WriteLine(IsBalanced("{[()]}")); // True
Console.WriteLine(IsBalanced("{[(])}")); // False
var stack = new CustomStack<int>();
stack.Push(1); stack.Push(2);
Console.WriteLine(stack.Pop()); // 2
Console.WriteLine(stack.Peek()); // 1
var queue = new CustomQueue<string>();
queue.Enqueue("a"); queue.Enqueue("b");
Console.WriteLine(queue.Dequeue()); // a
var cache = new TtlCache<string, int>(TimeSpan.FromMilliseconds(100));
cache.Set("answer", 42);
Console.WriteLine(cache.TryGet("answer", out int hit) ? hit.ToString() : "expired"); // 42
Thread.Sleep(150);
Console.WriteLine(cache.TryGet("answer", out _) ? "still there" : "expired"); // expired
static bool IsBalanced(string text)
{
var stack = new Stack<char>();
foreach (char c in text)
{
if (c is '(' or '[' or '{') stack.Push(c);
else if (c is ')' or ']' or '}')
{
if (stack.Count == 0) return false;
char open = stack.Pop();
if ((c == ')' && open != '(') || (c == ']' && open != '[') || (c == '}' && open != '{')) return false;
}
}
return stack.Count == 0;
}
public class CustomStack<T>
{
private T[] _items = new T[4];
private int _count;
public void Push(T item)
{
if (_count == _items.Length) Array.Resize(ref _items, _items.Length * 2);
_items[_count++] = item;
}
public T Pop()
{
if (_count == 0) throw new InvalidOperationException("The stack is empty.");
T item = _items[--_count];
_items[_count] = default!; // release the reference
return item;
}
public T Peek() => _count == 0 ? throw new InvalidOperationException("The stack is empty.") : _items[_count - 1];
}
public class CustomQueue<T>
{
private T[] _items = new T[4];
private int _head, _count;
public void Enqueue(T item)
{
if (_count == _items.Length) Grow();
_items[(_head + _count) % _items.Length] = item;
_count++;
}
public T Dequeue()
{
if (_count == 0) throw new InvalidOperationException("The queue is empty.");
T item = _items[_head];
_items[_head] = default!;
_head = (_head + 1) % _items.Length;
_count--;
return item;
}
private void Grow()
{
var bigger = new T[_items.Length * 2];
for (int i = 0; i < _count; i++) bigger[i] = _items[(_head + i) % _items.Length];
_items = bigger;
_head = 0;
}
}
public class TtlCache<TKey, TValue> where TKey : notnull
{
private readonly Dictionary<TKey, (TValue Value, DateTime Expires)> _entries = new();
private readonly TimeSpan _timeToLive;
private readonly object _lock = new();
public TtlCache(TimeSpan timeToLive) => _timeToLive = timeToLive;
public void Set(TKey key, TValue value)
{
lock (_lock) _entries[key] = (value, DateTime.UtcNow + _timeToLive);
}
public bool TryGet(TKey key, out TValue value)
{
lock (_lock)
{
if (_entries.TryGetValue(key, out var entry) && entry.Expires > DateTime.UtcNow)
{
value = entry.Value;
return true;
}
_entries.Remove(key); // drop expired entries lazily
value = default!;
return false;
}
}
}var employees = new List<Employee>
{
new("Asha", "Engineering", 90000), new("Ben", "Engineering", 75000),
new("Carla", "Sales", 60000), new("Dev", "Sales", 75000), new("Esha", "Sales", 60000),
};
foreach (var e in employees.OrderBy(e => e.Department).ThenByDescending(e => e.Salary))
Console.WriteLine($"{e.Department,-12} {e.Salary,7} {e.Name}");
var products = new[]
{
new Product("Keyboard", "Accessories", 25m, 10), new Product("Mouse", "Accessories", 10m, 20),
new Product("Monitor", "Displays", 150m, 4),
};
foreach (var group in products.GroupBy(p => p.Category))
Console.WriteLine($"{group.Key}: {group.Sum(p => p.Price * p.Quantity)}");
int? second = employees.Select(e => e.Salary).Distinct().OrderByDescending(s => s).Skip(1).Cast<int?>().FirstOrDefault();
Console.WriteLine(second); // 75000
public record Employee(string Name, string Department, int Salary);
public record Product(string Name, string Category, decimal Price, int Quantity);