Radix Sort Algorithm in DSA Javascript - Time & Space Complexity
Radix Sort sorts numbers by processing digits one at a time. Understanding its time complexity helps us see how it handles larger lists efficiently.
We want to know how the number of steps grows as the list and number size increase.
Analyze the time complexity of the following Radix Sort code snippet.
function radixSort(arr) {
const maxNum = Math.max(...arr);
let digitPlace = 1;
while (digitPlace <= maxNum) {
const buckets = Array.from({ length: 10 }, () => []);
for (const num of arr) {
const digit = Math.floor((num / digitPlace) % 10);
buckets[digit].push(num);
}
arr = [].concat(...buckets);
digitPlace *= 10;
}
return arr;
}
This code sorts an array of numbers by grouping them digit by digit from least to most significant.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over all numbers for each digit place.
- How many times: Once per digit place, which depends on the maximum number's length.
Each digit place requires scanning all numbers once. More numbers mean more work per digit. More digits mean more passes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (digits = 2) | ~20 (10 numbers x 2 digits) |
| 100 (digits = 3) | ~300 (100 numbers x 3 digits) |
| 1000 (digits = 4) | ~4000 (1000 numbers x 4 digits) |
Pattern observation: Operations grow linearly with number count and digit length combined.
Time Complexity: O(d x n)
This means the time grows linearly with the number of items and the number of digits in the largest number.
[X] Wrong: "Radix Sort is always faster than comparison sorts like Quick Sort."
[OK] Correct: Radix Sort depends on digit count and works best on fixed-length numbers. For large digit counts or non-integer data, comparison sorts may be faster.
Understanding Radix Sort's time complexity shows you can analyze algorithms beyond simple loops. This skill helps you explain and choose sorting methods wisely.
"What if we changed the base from 10 to 2 (binary digits)? How would the time complexity change?"
Practice
Radix Sort Algorithm?Solution
Step 1: Understand Radix Sort approach
Radix Sort sorts numbers by processing each digit separately, starting from the least significant digit (rightmost).Step 2: Compare with other sorting methods
Unlike comparison-based sorts, Radix Sort groups numbers by digits without direct comparisons between whole numbers.Final Answer:
Sort numbers digit by digit starting from the least significant digit -> Option DQuick Check:
Radix Sort = Digit by digit sorting [OK]
- Thinking Radix Sort compares whole numbers directly
- Confusing Radix Sort with quicksort or mergesort
- Assuming it sorts from most significant digit first
Solution
Step 1: Understand bucket initialization
We need 10 separate arrays (buckets) for digits 0-9. UsingArray.fromwith a function creates independent arrays.Step 2: Why other options fail
const buckets = new Array(10).fill([]); fills with the same array reference, causing all buckets to share one array. const buckets = [].map(() => []); fails becausemapon empty array does nothing. const buckets = Array(10).fill(null); fills with null, not arrays.Final Answer:
const buckets = Array.from({ length: 10 }, () => []); -> Option CQuick Check:
Use Array.from with function for separate buckets [OK]
- Using fill([]) creates shared references
- Using map on uninitialized array returns empty
- Filling buckets with null instead of arrays
[170, 45, 75, 90, 802, 24, 2, 66]?
function getDigit(num, place) {
return Math.floor(Math.abs(num) / Math.pow(10, place)) % 10;
}
function radixSort(arr) {
let maxDigit = Math.floor(Math.log10(Math.max(...arr))) + 1;
for (let k = 0; k < maxDigit; k++) {
let buckets = Array.from({ length: 10 }, () => []);
for (let num of arr) {
buckets[getDigit(num, k)].push(num);
}
arr = [].concat(...buckets);
}
return arr;
}
console.log(radixSort([170, 45, 75, 90, 802, 24, 2, 66]));Solution
Step 1: Understand digit extraction and sorting
The code sorts numbers by each digit from least significant (units) to most significant. After each pass, numbers are grouped by that digit.Step 2: Trace sorting passes
After sorting by units digit, then tens, then hundreds, the array becomes fully sorted ascending: [2, 24, 45, 66, 75, 90, 170, 802].Final Answer:
[2, 24, 45, 66, 75, 90, 170, 802] -> Option BQuick Check:
Radix Sort output = Sorted ascending array [OK]
- Confusing original array with sorted output
- Misunderstanding digit extraction order
- Assuming sorting is descending
function radixSort(arr) {
let maxDigit = Math.floor(Math.log10(Math.max(...arr))) + 1;
for (let k = 0; k <= maxDigit; k++) {
let buckets = Array.from({ length: 10 }, () => []);
for (let num of arr) {
buckets[Math.floor(num / Math.pow(10, k)) % 10].push(num);
}
arr = [].concat(...buckets);
}
return arr;
}Solution
Step 1: Analyze loop range for digit passes
The loop runs from 0 to maxDigit inclusive, causing one extra pass beyond needed digits.Step 2: Fix loop condition
Changingk <= maxDigittok < maxDigitensures exactly maxDigit passes, avoiding unnecessary iteration.Final Answer:
Change loop condition to k < maxDigit instead of <= maxDigit -> Option AQuick Check:
Loop runs maxDigit times, not maxDigit+1 [OK]
- Using <= causes extra unnecessary pass
- Initializing buckets incorrectly with shared arrays
- Changing floor to ceil breaks digit count
[170, -45, 75, -90, 802, 24, -2, 66]. Which approach correctly adapts Radix Sort for this case?Solution
Step 1: Understand Radix Sort limitation
Radix Sort works only on non-negative integers because it sorts digits from least significant to most significant.Step 2: Adapt for negatives
Separate negatives and positives. Sort positives normally. For negatives, sort their absolute values, then reverse the result to get correct order. Finally, combine negatives (in reversed order) before positives.Final Answer:
Separate negative and positive numbers, sort positives with Radix Sort, sort negatives by absolute value then reverse, then combine -> Option AQuick Check:
Separate negatives and positives, sort separately [OK]
- Trying to sort negatives directly with Radix Sort
- Ignoring negative numbers in sorting
- Sorting numbers as strings causing wrong order
Ready to prove it?
Pass the test and this pattern moves unknown
