Library

Volume 3 · Coding Problems & Data Structures

Notebook
Sign in

Section 25

Top Coding Problems by Pattern (Python + C#)

2,887 words · about 13 min

25.1 Two Sum (Hash Map)

Python

def two_sum(nums: list[int], target: int) -> list[int]:
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

assert two_sum([2, 7, 11, 15], 9) == [0, 1]

C#

public static int[] TwoSum(int[] nums, int target)
{
    var seen = new Dictionary<int, int>();
    for (int i = 0; i < nums.Length; i++)
    {
        int complement = target - nums[i];
        if (seen.TryGetValue(complement, out int idx))
            return new[] { idx, i };
        seen[nums[i]] = i;
    }
    return Array.Empty<int>();
}

25.2 Two Sum II — Sorted Input (Two Pointers)

Python

def two_sum_sorted(nums: list[int], target: int) -> list[int]:
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return [left + 1, right + 1]  # 1-indexed, as in LeetCode
        elif total < target:
            left += 1
        else:
            right -= 1
    return []

C#

public static int[] TwoSumSorted(int[] nums, int target)
{
    int left = 0, right = nums.Length - 1;
    while (left < right)
    {
        int total = nums[left] + nums[right];
        if (total == target) return new[] { left + 1, right + 1 };
        if (total < target) left++;
        else right--;
    }
    return Array.Empty<int>();
}

25.3 3Sum (Two Pointers on Sorted Array)

Python

def three_sum(nums: list[int]) -> list[list[int]]:
    nums.sort()
    result = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue  # skip duplicates
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total == 0:
                result.append([nums[i], nums[left], nums[right]])
                while left < right and nums[left] == nums[left + 1]:
                    left += 1
                while left < right and nums[right] == nums[right - 1]:
                    right -= 1
                left += 1
                right -= 1
            elif total < 0:
                left += 1
            else:
                right -= 1
    return result

assert three_sum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]]

C#

public static List<List<int>> ThreeSum(int[] nums)
{
    Array.Sort(nums);
    var result = new List<List<int>>();

    for (int i = 0; i < nums.Length - 2; i++)
    {
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        int left = i + 1, right = nums.Length - 1;

        while (left < right)
        {
            int total = nums[i] + nums[left] + nums[right];
            if (total == 0)
            {
                result.Add(new List<int> { nums[i], nums[left], nums[right] });
                while (left < right && nums[left] == nums[left + 1]) left++;
                while (left < right && nums[right] == nums[right - 1]) right--;
                left++; right--;
            }
            else if (total < 0) left++;
            else right--;
        }
    }
    return result;
}

25.4 Merge Intervals

Python

def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged

assert merge_intervals([[1,3],[2,6],[8,10],[15,18]]) == [[1,6],[8,10],[15,18]]

C#

public static List<int[]> MergeIntervals(int[][] intervals)
{
    if (intervals.Length == 0) return new List<int[]>();
    Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));

    var merged = new List<int[]> { intervals[0] };
    for (int i = 1; i < intervals.Length; i++)
    {
        var last = merged[^1];
        if (intervals[i][0] <= last[1])
            last[1] = Math.Max(last[1], intervals[i][1]);
        else
            merged.Add(intervals[i]);
    }
    return merged;
}

25.5 Top K Frequent Elements (Bucket Sort — O(n))

Python

from collections import Counter

def top_k_frequent(nums: list[int], k: int) -> list[int]:
    count = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]
    for num, freq in count.items():
        buckets[freq].append(num)

    result = []
    for freq in range(len(buckets) - 1, 0, -1):
        for num in buckets[freq]:
            result.append(num)
            if len(result) == k:
                return result
    return result

C#

public static List<int> TopKFrequentBucket(int[] nums, int k)
{
    var counts = new Dictionary<int, int>();
    foreach (var n in nums) counts[n] = counts.GetValueOrDefault(n) + 1;

    var buckets = new List<int>[nums.Length + 1];
    for (int i = 0; i <= nums.Length; i++) buckets[i] = new List<int>();
    foreach (var kv in counts) buckets[kv.Value].Add(kv.Key);

    var result = new List<int>();
    for (int freq = nums.Length; freq >= 1 && result.Count < k; freq--)
    {
        foreach (var num in buckets[freq])
        {
            result.Add(num);
            if (result.Count == k) break;
        }
    }
    return result;
}

25.6 Longest Substring Without Repeating Characters (Sliding Window)

Python

def longest_unique_substring(s: str) -> int:
    char_index = {}
    max_length = 0
    start = 0
    for end, char in enumerate(s):
        if char in char_index and char_index[char] >= start:
            start = char_index[char] + 1
        char_index[char] = end
        max_length = max(max_length, end - start + 1)
    return max_length

assert longest_unique_substring("abcabcbb") == 3

C#

public static int LongestUniqueSubstring(string s)
{
    var charIndex = new Dictionary<char, int>();
    int maxLength = 0, start = 0;

    for (int end = 0; end < s.Length; end++)
    {
        char c = s[end];
        if (charIndex.TryGetValue(c, out int idx) && idx >= start)
            start = idx + 1;
        charIndex[c] = end;
        maxLength = Math.Max(maxLength, end - start + 1);
    }
    return maxLength;
}

25.7 Course Schedule / Topological Sort (Cycle Detection in DAG)

Python

from collections import defaultdict, deque

def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool:
    """Kahn's algorithm: True if all courses can be completed (no cycle)."""
    graph = defaultdict(list)
    in_degree = [0] * num_courses

    for course, prereq in prerequisites:
        graph[prereq].append(course)
        in_degree[course] += 1

    queue = deque([c for c in range(num_courses) if in_degree[c] == 0])
    completed = 0

    while queue:
        node = queue.popleft()
        completed += 1
        for neighbor in graph[node]:
            in_degree[neighbor] -= 1
            if in_degree[neighbor] == 0:
                queue.append(neighbor)

    return completed == num_courses

assert can_finish(2, [[1, 0]]) == True
assert can_finish(2, [[1, 0], [0, 1]]) == False  # cycle

C#

public static bool CanFinish(int numCourses, int[][] prerequisites)
{
    var graph = new List<int>[numCourses];
    for (int i = 0; i < numCourses; i++) graph[i] = new List<int>();
    var inDegree = new int[numCourses];

    foreach (var p in prerequisites)
    {
        int course = p[0], prereq = p[1];
        graph[prereq].Add(course);
        inDegree[course]++;
    }

    var queue = new Queue<int>();
    for (int i = 0; i < numCourses; i++)
        if (inDegree[i] == 0) queue.Enqueue(i);

    int completed = 0;
    while (queue.Count > 0)
    {
        var node = queue.Dequeue();
        completed++;
        foreach (var neighbor in graph[node])
        {
            if (--inDegree[neighbor] == 0)
                queue.Enqueue(neighbor);
        }
    }
    return completed == numCourses;
}

25.8 Word Ladder (BFS Shortest Transformation)

Python

from collections import deque

def word_ladder_length(begin_word: str, end_word: str, word_list: list[str]) -> int:
    """Shortest transformation sequence length, changing 1 letter at a time."""
    word_set = set(word_list)
    if end_word not in word_set:
        return 0

    queue = deque([(begin_word, 1)])
    visited = {begin_word}

    while queue:
        word, steps = queue.popleft()
        if word == end_word:
            return steps

        for i in range(len(word)):
            for c in "abcdefghijklmnopqrstuvwxyz":
                candidate = word[:i] + c + word[i + 1:]
                if candidate in word_set and candidate not in visited:
                    visited.add(candidate)
                    queue.append((candidate, steps + 1))

    return 0

assert word_ladder_length("hit", "cog", ["hot","dot","dog","lot","log","cog"]) == 5

C#

public static int WordLadderLength(string beginWord, string endWord, IList<string> wordList)
{
    var wordSet = new HashSet<string>(wordList);
    if (!wordSet.Contains(endWord)) return 0;

    var queue = new Queue<(string Word, int Steps)>();
    queue.Enqueue((beginWord, 1));
    var visited = new HashSet<string> { beginWord };

    while (queue.Count > 0)
    {
        var (word, steps) = queue.Dequeue();
        if (word == endWord) return steps;

        var chars = word.ToCharArray();
        for (int i = 0; i < chars.Length; i++)
        {
            char original = chars[i];
            for (char c = 'a'; c <= 'z'; c++)
            {
                if (c == original) continue;
                chars[i] = c;
                var candidate = new string(chars);
                if (wordSet.Contains(candidate) && visited.Add(candidate))
                    queue.Enqueue((candidate, steps + 1));
            }
            chars[i] = original;
        }
    }
    return 0;
}

25.9 Find Median from Data Stream (Two Heaps)

Python

import heapq

class MedianFinder:
    """
    Max-heap for the lower half (stored negated, since Python's heapq is a min-heap),
    min-heap for the upper half. Keeps sizes within 1 of each other.
    """

    def __init__(self):
        self.lower = []   # max-heap (negated values)
        self.upper = []   # min-heap

    def add_num(self, num: int) -> None:
        heapq.heappush(self.lower, -num)
        heapq.heappush(self.upper, -heapq.heappop(self.lower))

        if len(self.upper) > len(self.lower):
            heapq.heappush(self.lower, -heapq.heappop(self.upper))

    def find_median(self) -> float:
        if len(self.lower) > len(self.upper):
            return -self.lower[0]
        return (-self.lower[0] + self.upper[0]) / 2.0

C#

using System.Collections.Generic;

public class MedianFinder
{
    private readonly PriorityQueue<int, int> _lower = new(Comparer<int>.Create((a, b) => b.CompareTo(a))); // max-heap
    private readonly PriorityQueue<int, int> _upper = new(); // min-heap

    public void AddNum(int num)
    {
        _lower.Enqueue(num, num);
        _upper.Enqueue(_lower.Peek(), _lower.Dequeue());

        if (_upper.Count > _lower.Count)
        {
            var val = _upper.Dequeue();
            _lower.Enqueue(val, val);
        }
    }

    public double FindMedian()
    {
        if (_lower.Count > _upper.Count) return _lower.Peek();
        return (_lower.Peek() + _upper.Peek()) / 2.0;
    }
}

25.10 Kth Largest Element in an Array (Quickselect — O(n) average)

Python

import random

def find_kth_largest(nums: list[int], k: int) -> int:
    """Quickselect: O(n) average, O(n^2) worst case (mitigated by random pivot)."""
    k = len(nums) - k  # convert to kth smallest index

    def partition(left, right, pivot_index):
        pivot = nums[pivot_index]
        nums[pivot_index], nums[right] = nums[right], nums[pivot_index]
        store_index = left
        for i in range(left, right):
            if nums[i] < pivot:
                nums[store_index], nums[i] = nums[i], nums[store_index]
                store_index += 1
        nums[right], nums[store_index] = nums[store_index], nums[right]
        return store_index

    def select(left, right):
        if left == right:
            return nums[left]
        pivot_index = random.randint(left, right)
        pivot_index = partition(left, right, pivot_index)
        if k == pivot_index:
            return nums[k]
        elif k < pivot_index:
            return select(left, pivot_index - 1)
        else:
            return select(pivot_index + 1, right)

    return select(0, len(nums) - 1)

assert find_kth_largest([3,2,1,5,6,4], 2) == 5

C#

using System;

public static class KthLargestFinder
{
    private static readonly Random Rng = new();

    public static int FindKthLargest(int[] nums, int k)
    {
        int target = nums.Length - k;
        return Select(nums, 0, nums.Length - 1, target);
    }

    private static int Select(int[] nums, int left, int right, int k)
    {
        if (left == right) return nums[left];
        int pivotIndex = Rng.Next(left, right + 1);
        pivotIndex = Partition(nums, left, right, pivotIndex);

        if (k == pivotIndex) return nums[k];
        return k < pivotIndex
            ? Select(nums, left, pivotIndex - 1, k)
            : Select(nums, pivotIndex + 1, right, k);
    }

    private static int Partition(int[] nums, int left, int right, int pivotIndex)
    {
        int pivot = nums[pivotIndex];
        (nums[pivotIndex], nums[right]) = (nums[right], nums[pivotIndex]);
        int storeIndex = left;

        for (int i = left; i < right; i++)
        {
            if (nums[i] < pivot)
            {
                (nums[storeIndex], nums[i]) = (nums[i], nums[storeIndex]);
                storeIndex++;
            }
        }
        (nums[right], nums[storeIndex]) = (nums[storeIndex], nums[right]);
        return storeIndex;
    }
}

25.11 Number of Islands (Grid BFS/DFS)

Python

def num_islands(grid: list[list[str]]) -> int:
    if not grid:
        return 0
    rows, cols = len(grid), len(grid[0])
    count = 0

    def dfs(r, c):
        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != '1':
            return
        grid[r][c] = '0'
        dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1)

    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1':
                count += 1
                dfs(r, c)
    return count

C#

public static int NumIslands(char[][] grid)
{
    if (grid == null || grid.Length == 0) return 0;
    int rows = grid.Length, cols = grid[0].Length;
    int count = 0;

    void Dfs(int r, int c)
    {
        if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] != '1') return;
        grid[r][c] = '0';
        Dfs(r + 1, c); Dfs(r - 1, c); Dfs(r, c + 1); Dfs(r, c - 1);
    }

    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++)
            if (grid[r][c] == '1') { count++; Dfs(r, c); }

    return count;
}

25.12 Coin Change (Bottom-Up DP)

Python

def coin_change(coins: list[int], amount: int) -> int:
    dp = [float('inf')] * (amount + 1)
    dp[0] = 0
    for i in range(1, amount + 1):
        for coin in coins:
            if coin <= i:
                dp[i] = min(dp[i], dp[i - coin] + 1)
    return dp[amount] if dp[amount] != float('inf') else -1

C#

public static int CoinChange(int[] coins, int amount)
{
    var dp = new int[amount + 1];
    Array.Fill(dp, int.MaxValue - 1);
    dp[0] = 0;

    for (int i = 1; i <= amount; i++)
        foreach (var coin in coins)
            if (coin <= i)
                dp[i] = Math.Min(dp[i], dp[i - coin] + 1);

    return dp[amount] >= int.MaxValue - 1 ? -1 : dp[amount];
}

25.13 LCA of a Binary Search Tree

Python

def lowest_common_ancestor(root, p, q):
    node = root
    while node:
        if p.val < node.val and q.val < node.val:
            node = node.left
        elif p.val > node.val and q.val > node.val:
            node = node.right
        else:
            return node
    return None

C#

public static TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
    var node = root;
    while (node != null)
    {
        if (p.Val < node.Val && q.Val < node.Val) node = node.Left;
        else if (p.Val > node.Val && q.Val > node.Val) node = node.Right;
        else return node;
    }
    return null!;
}

Complexity summary for section 25: All patterns above run in O(n), O(n log n), or O(V+E) time as annotated inline — this is exactly the range interviewers expect for a 25–35 minute coding round. If you finish early, always volunteer the follow-up: “here’s how I’d handle this at 10x scale / with duplicate keys / streamed rather than batch input.”