Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Counting Sort Algorithm in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Counting Sort Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Counting Sort on a small array
What is the output of the following counting sort implementation on the array [4, 2, 2, 8, 3, 3, 1]?
DSA Javascript
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;
}

console.log(countingSort([4, 2, 2, 8, 3, 3, 1]));
A[1, 2, 3, 4, 8]
B[1, 2, 2, 3, 3, 4, 8]
C[8, 4, 3, 3, 2, 2, 1]
D[1, 1, 2, 2, 3, 3, 4, 8]
Attempts:
2 left
💡 Hint
Counting sort counts how many times each number appears and then rebuilds the array in order.
🧠 Conceptual
intermediate
1:30remaining
Counting Sort Stability Property
Which statement correctly describes the stability of counting sort?
ACounting sort is unstable because it uses a hash map internally.
BCounting sort is unstable because it rearranges equal elements randomly.
CCounting sort is stable only if the input array is already sorted.
DCounting sort is stable because it preserves the relative order of equal elements.
Attempts:
2 left
💡 Hint
Think about whether equal numbers keep their original order after sorting.
🔧 Debug
advanced
2:00remaining
Identify the error in this counting sort code
What error will this code produce when run on the array [3, 1, 2]?
DSA Javascript
function countingSort(arr) {
  const max = Math.max(...arr);
  const count = new Array(max).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;
}

console.log(countingSort([3, 1, 2]));
ATypeError: Cannot read property '3' of undefined
BRangeError: Maximum call stack size exceeded
COutput: [1, 2, 3]
DReferenceError: max is not defined
Attempts:
2 left
💡 Hint
Check how the count array is created and accessed.
🚀 Application
advanced
2:30remaining
Counting Sort with Negative Numbers
Given the array [-5, -10, 0, -3, 8, 5, -1, 10], which approach correctly adapts counting sort to handle negative numbers?
AConvert all numbers to strings and sort lexicographically.
BIgnore negative numbers and sort only positive numbers using counting sort.
CShift all numbers by adding the absolute value of the minimum number before sorting, then shift back after sorting.
DUse counting sort directly without changes; it handles negatives automatically.
Attempts:
2 left
💡 Hint
Counting sort uses array indices as counts, so negative indices are invalid.
❓ Predict Output
expert
2:30remaining
Output of Counting Sort with Frequency Array
What is the output of this code snippet?
DSA Javascript
function countingSort(arr) {
  const max = Math.max(...arr);
  const count = new Array(max + 1).fill(0);
  for (const num of arr) {
    count[num]++;
  }
  const result = [];
  for (let i = 0; i < count.length; i++) {
    for (let j = 0; j < count[i]; j++) {
      result.push(i);
    }
  }
  return result;
}

const input = [2, 5, 3, 0, 2, 3, 0, 3];
console.log(countingSort(input));
A[0, 0, 2, 2, 3, 3, 3, 5]
B[0, 0, 2, 3, 3, 3, 5]
C[0, 0, 2, 3, 3, 5]
D[0, 0, 2, 3, 5]
Attempts:
2 left
💡 Hint
Count how many times each number appears and list them in order.

Practice

(1/5)
1. What is the main idea behind the Counting Sort Algorithm?
easy
A. Swap adjacent elements if they are in wrong order repeatedly
B. Compare each element with every other element to sort
C. Count the occurrences of each element and use counts to place elements in order
D. Divide the array into halves and sort recursively

Solution

  1. Step 1: Understand Counting Sort principle

    Counting sort counts how many times each value appears in the input array.
  2. Step 2: Use counts to place elements

    Using these counts, it calculates positions to place each element in the sorted output.
  3. Final Answer:

    Count the occurrences of each element and use counts to place elements in order -> Option C
  4. Quick Check:

    Counting elements = Counting Sort [OK]
Hint: Counting sort counts elements, no comparisons needed [OK]
Common Mistakes:
  • Thinking counting sort compares elements like bubble sort
  • Confusing counting sort with divide and conquer methods
  • Assuming counting sort works on all data types
2. Which of the following is the correct way to initialize the count array in Counting Sort for input array arr with maximum value maxVal in JavaScript?
easy
A. const count = new Array().fill(maxVal + 1);
B. const count = new Array(maxVal).fill(0);
C. const count = new Array(arr.length).fill(0);
D. const count = new Array(maxVal + 1).fill(0);

Solution

  1. Step 1: Determine size of count array

    The count array must cover all values from 0 to maxVal, so size is maxVal + 1.
  2. Step 2: Initialize count array with zeros

    Use new Array(maxVal + 1).fill(0) to create and fill with zeros.
  3. Final Answer:

    const count = new Array(maxVal + 1).fill(0); -> Option D
  4. Quick Check:

    Count array size = maxVal + 1 [OK]
Hint: Count array length = max value + 1 [OK]
Common Mistakes:
  • 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
3. What will be the output of the following JavaScript code using Counting Sort?
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]));
medium
A. [1, 2, 2, 3, 3, 4, 8]
B. [8, 4, 3, 3, 2, 2, 1]
C. [1, 2, 3, 4, 8]
D. [4, 2, 2, 8, 3, 3, 1]

Solution

  1. 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.
  2. Step 2: Build sorted array using counts

    Push each number count[i] times in ascending order: 1, 2, 2, 3, 3, 4, 8.
  3. Final Answer:

    [1, 2, 2, 3, 3, 4, 8] -> Option A
  4. Quick Check:

    Sorted array matches counting sort output [OK]
Hint: Counting sort output is sorted array with duplicates in order [OK]
Common Mistakes:
  • Returning original array instead of sorted
  • Reversing order by mistake
  • Missing duplicates in output
4. Identify the bug in this Counting Sort implementation and select the fix:
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;
}
medium
A. Change count array size to maxVal + 1 and loop to i <= maxVal
B. Initialize count array with zeros using fill(1)
C. Use for loop from i = 1 to maxVal instead of 0
D. Remove the while loop and use if condition instead

Solution

  1. Step 1: Check count array size and loop range

    Count array size is maxVal but should be maxVal + 1 to include maxVal index.
  2. Step 2: Fix loop to include maxVal index

    Loop should run from 0 to maxVal inclusive (i <= maxVal) to cover all counts.
  3. Final Answer:

    Change count array size to maxVal + 1 and loop to i <= maxVal -> Option A
  4. Quick Check:

    Count array size and loop range must match maxVal + 1 [OK]
Hint: Count array size = maxVal + 1; loop to i <= maxVal [OK]
Common Mistakes:
  • Using wrong count array size causing index errors
  • Looping less than needed, missing maxVal counts
  • Changing fill value incorrectly
5. Given an array 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?
hard
A. Use counting sort on full range but skip pushing elements outside 1 to 4
B. Count only elements between 1 and 4, then output sorted elements in that range
C. Sort entire array normally and then remove elements outside 1 to 4
D. Filter array first, then apply counting sort on filtered array

Solution

  1. Step 1: Count only elements in range 1 to 4

    Ignore elements outside 1 to 4 while counting to focus sorting on this range.
  2. Step 2: Output sorted elements only in that range

    Build sorted array using counts only for values 1 to 4, ignoring others.
  3. Final Answer:

    Count only elements between 1 and 4, then output sorted elements in that range -> Option B
  4. Quick Check:

    Counting and output limited to range [1,4] [OK]
Hint: Count and output only target range elements [OK]
Common Mistakes:
  • Sorting full array then filtering, wasting effort
  • Counting full range but skipping output incorrectly
  • Filtering after sorting instead of before
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard