QA
Beginner LevelData Structures & Algorithms

What are Counting Sort and Radix Sort and when do they beat O(N log N)?

ā“ Interview Prompt: Explain Counting Sort (O(N+K)) and Radix Sort (O(N*d)), when they outperform comparison-based sorts, and their limitations.

Counting Sort: $O(N + K)$ where $K$ = range of values

•
Count frequency of each value → compute cumulative counts → place elements.
•
Constraint: Only works with non-negative integer keys in a bounded range $[0, K]$.
•
Ideal when $K = O(N)$ (e.g., sorting ages 0–120, exam scores 0–100).

Radix Sort: $O(N \times d)$ where $d$ = number of digits

•
Sort digit by digit from least significant to most significant using a stable sub-sort (Counting Sort).
•
Works on integers or fixed-length strings.
•
Beats $O(N \log N)$ when $d \ll \log N$ and $K = O(N)$.

Code Implementation Example

typescript
// Counting Sort — O(N + K)
function countingSort(arr: number[], maxVal: number): number[] {
  const count = new Array(maxVal + 1).fill(0);
  for (const n of arr) count[n]++;
  const sorted: number[] = [];
  for (let i = 0; i <= maxVal; i++) {
    while (count[i]-- > 0) sorted.push(i);
  }
  return sorted;
}

console.log(countingSort([4, 2, 2, 8, 3, 3, 1], 8));
// [1, 2, 2, 3, 3, 4, 8]
šŸ’”Counting Sort achieving O(N+K) by bypassing comparison operations.
šŸŽÆ Interview Key Takeaway

Counting/Radix Sort break the O(N log N) comparison barrier when input values are integers in a bounded range.

#DSA#Counting Sort#Radix Sort#Non-Comparison Sort#Beginner
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?