Bird
Raised Fist0
DSA Javascriptprogramming~5 mins

Counting Sort Algorithm in DSA Javascript - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is the main idea behind the Counting Sort Algorithm?
Counting Sort counts how many times each number appears, then uses these counts to place numbers in the right order without comparing them directly.
Click to reveal answer
beginner
Which type of data is Counting Sort best suited for?
Counting Sort works best for sorting numbers that are small and within a known range, like ages from 0 to 100.
Click to reveal answer
intermediate
What is the time complexity of Counting Sort and why?
Counting Sort runs in O(n + k) time, where n is the number of elements and k is the range of input values, because it counts and places elements without comparisons.
Click to reveal answer
intermediate
How does Counting Sort ensure stability (keeping original order of equal elements)?
Counting Sort uses the counts to find exact positions for elements and places them from right to left, preserving the order of equal elements.
Click to reveal answer
intermediate
What is a limitation of Counting Sort compared to comparison-based sorts?
Counting Sort needs extra space proportional to the range of input values, so it is not efficient if the range is very large compared to the number of elements.
Click to reveal answer
What does Counting Sort use to sort elements?
ACounting how many times each value appears
BComparing elements pairwise
CSwapping elements randomly
DDividing elements into halves
Which of these is a requirement for Counting Sort to work efficiently?
AInput must be floating point numbers
BInput must be already sorted
CInput values must be strings
DInput values must be integers within a small range
What is the space complexity of Counting Sort?
AO(n + k), where k is the range of input values
BO(1), constant space
CO(n log n)
DO(n^2)
How does Counting Sort place elements to maintain stability?
ABy swapping elements randomly
BBy placing elements from right to left using counts
CBy sorting elements in reverse order
DBy ignoring original order
Counting Sort is NOT suitable when:
AThe input contains only positive integers
BThe input is small and within a small range
CThe range of input values is very large
DThe input is already sorted
Explain how Counting Sort works step-by-step on a small list of numbers.
Think about counting first, then using counts to find positions.
You got /4 concepts.
    What are the advantages and disadvantages of Counting Sort compared to other sorting algorithms?
    Consider speed and memory use.
    You got /2 concepts.

      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