Counting Sort Algorithm in DSA Javascript - Time & Space Complexity
Counting Sort is a special sorting method that works well when numbers are in a small range.
We want to understand how the time it takes grows as the list size and number range grow.
Analyze the time complexity of the following code snippet.
function countingSort(arr) {
const max = Math.max(...arr);
const count = new Array(max + 1).fill(0);
for (const num of arr) {
count[num]++;
}
let sortedIndex = 0;
for (let i = 0; i < count.length; i++) {
while (count[i] > 0) {
arr[sortedIndex++] = i;
count[i]--;
}
}
return arr;
}
This code sorts an array by counting how many times each number appears, then rebuilding the sorted array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Counting each number in the input array and then rebuilding the sorted array.
- How many times: The first loop runs once for each element in the input (n times). The second loop runs once for each number in the range (k times), and inside it, the inner loop runs as many times as the count of that number.
Explain the growth pattern intuitively.
| Input Size (n) | Range Size (k) | Approx. Operations |
|---|---|---|
| 10 | 5 | About 10 + 5 = 15 operations |
| 100 | 20 | About 100 + 20 = 120 operations |
| 1000 | 100 | About 1000 + 100 = 1100 operations |
Pattern observation: The time grows roughly with the sum of the input size and the range size.
Time Complexity: O(n + k)
This means the time grows linearly with both the number of items and the range of numbers.
[X] Wrong: "Counting Sort always runs in linear time regardless of the number range."
[OK] Correct: If the range of numbers (k) is very large compared to the input size (n), the time depends on k too, so it can be slower.
Understanding Counting Sort's time complexity helps you choose the right sorting method based on data size and range, a useful skill in real coding tasks.
"What if the input array contains negative numbers? How would the time complexity change?"
Practice
Counting Sort Algorithm?Solution
Step 1: Understand Counting Sort principle
Counting sort counts how many times each value appears in the input array.Step 2: Use counts to place elements
Using these counts, it calculates positions to place each element in the sorted output.Final Answer:
Count the occurrences of each element and use counts to place elements in order -> Option CQuick Check:
Counting elements = Counting Sort [OK]
- Thinking counting sort compares elements like bubble sort
- Confusing counting sort with divide and conquer methods
- Assuming counting sort works on all data types
arr with maximum value maxVal in JavaScript?Solution
Step 1: Determine size of count array
The count array must cover all values from 0 to maxVal, so size is maxVal + 1.Step 2: Initialize count array with zeros
Usenew Array(maxVal + 1).fill(0)to create and fill with zeros.Final Answer:
const count = new Array(maxVal + 1).fill(0); -> Option DQuick Check:
Count array size = maxVal + 1 [OK]
- Using maxVal instead of maxVal + 1 for array size
- Using input array length instead of maxVal
- Incorrectly filling array with maxVal + 1 instead of zeros
function countingSort(arr) {
const maxVal = Math.max(...arr);
const count = new Array(maxVal + 1).fill(0);
for (const num of arr) count[num]++;
let sorted = [];
for (let i = 0; i <= maxVal; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
console.log(countingSort([4, 2, 2, 8, 3, 3, 1]));Solution
Step 1: Count occurrences of each number
Count array after counting: count[1]=1, count[2]=2, count[3]=2, count[4]=1, count[8]=1.Step 2: Build sorted array using counts
Push each number count[i] times in ascending order: 1, 2, 2, 3, 3, 4, 8.Final Answer:
[1, 2, 2, 3, 3, 4, 8] -> Option AQuick Check:
Sorted array matches counting sort output [OK]
- Returning original array instead of sorted
- Reversing order by mistake
- Missing duplicates in output
function countingSort(arr) {
const maxVal = Math.max(...arr);
const count = new Array(maxVal).fill(0);
for (const num of arr) {
count[num]++;
}
let sorted = [];
for (let i = 0; i < maxVal; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}Solution
Step 1: Check count array size and loop range
Count array size is maxVal but should be maxVal + 1 to include maxVal index.Step 2: Fix loop to include maxVal index
Loop should run from 0 to maxVal inclusive (i <= maxVal) to cover all counts.Final Answer:
Change count array size to maxVal + 1 and loop to i <= maxVal -> Option AQuick Check:
Count array size and loop range must match maxVal + 1 [OK]
- Using wrong count array size causing index errors
- Looping less than needed, missing maxVal counts
- Changing fill value incorrectly
arr = [5, 3, 0, 2, 3, 5, 1], how would you modify Counting Sort to sort only the elements between 1 and 4 inclusive, ignoring others?Solution
Step 1: Count only elements in range 1 to 4
Ignore elements outside 1 to 4 while counting to focus sorting on this range.Step 2: Output sorted elements only in that range
Build sorted array using counts only for values 1 to 4, ignoring others.Final Answer:
Count only elements between 1 and 4, then output sorted elements in that range -> Option BQuick Check:
Counting and output limited to range [1,4] [OK]
- Sorting full array then filtering, wasting effort
- Counting full range but skipping output incorrectly
- Filtering after sorting instead of before
Ready to prove it?
Pass the test and this pattern moves unknown
