Algorithms Interview Questions

Sorting

Sorting algorithms overview

Common sorts:

  • Bubble/Insertion: simple, O(n^2)
  • Merge/Quick: O(n log n) average; merge stable; quick in-place
  • Counting/Radix: linear for integers in range
Graphs

BFS vs DFS

BFS explores level by level (shortest path in unweighted). DFS goes deep first (cycle detection, topological sort).

Optimization

Dynamic programming

Break problems into overlapping subproblems; store results (memoization/tabulation).

// Fibonacci with memo
const memo = new Map();
function fib(n){
  if(n<2) return n;
  if(memo.has(n)) return memo.get(n);
  const v=fib(n-1)+fib(n-2);
  memo.set(n,v); return v;
}
Optimization

Greedy algorithms

Make locally optimal choices hoping for global optimum (activity selection, coin change for canonical systems).

Techniques

Recursion tips

Define base case; progress towards it; watch stack depth; convert to iteration if needed.

Techniques

Two pointers

Use two indices moving towards each other or in tandem (reverse array, remove duplicates, sum pairs).

Techniques

Sliding window

Maintain a window to track substring/subarray properties (max sum, longest unique substring).

Graphs

Dijkstra's algorithm

Finds shortest paths in weighted graphs with non-negative edges using a priority queue (min-heap).

Graphs

Topological sort

Orders DAG nodes so edges go from earlier to later nodes; implemented via DFS or Kahn's algorithm.

Strings

KMP string search

Preprocesses pattern to build LPS array for linear-time substring search; avoids redundant comparisons.

Complexity

Amortized analysis

Average cost per operation over sequences, e.g., dynamic array appends or union-find path compression.

Theory

NP-Completeness

NP problems verifiable in polynomial time; NP-complete are the hardest in NP (SAT, Traveling Salesman). Use reductions and approximations.

Paradigms

Divide and Conquer

Break problems into subproblems, solve recursively, and combine (merge sort, quicksort, FFT).

Paradigms

Dynamic Programming patterns

Overlapping subproblems and optimal substructure; common patterns like knapsack, LIS, edit distance.

Paradigms

Greedy algorithms

Make locally optimal choices; correctness via exchange argument or matroid structure (interval scheduling, Huffman coding).

Search

Binary search variants

Lower/upper bound, first/last occurrence, searching on answer space; careful with mid and termination conditions.

Selection

Quickselect

Find k-th smallest in average O(n) using partitioning; worst-case O(n^2), can be optimized with median-of-medians.