Challenge - 5 Problems
Counting Sort Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Counting Sort on a small array
What is the output of the following Java code that uses counting sort on the array [4, 2, 2, 8, 3, 3, 1]?
DSA Java
import java.util.Arrays; public class Main { public static void countingSort(int[] arr) { int max = Arrays.stream(arr).max().getAsInt(); int[] count = new int[max + 1]; for (int num : arr) { count[num]++; } int index = 0; for (int i = 0; i < count.length; i++) { while (count[i] > 0) { arr[index++] = i; count[i]--; } } } public static void main(String[] args) { int[] arr = {4, 2, 2, 8, 3, 3, 1}; countingSort(arr); System.out.println(Arrays.toString(arr)); } }
Attempts:
2 left
💡 Hint
Counting sort counts how many times each number appears and then rebuilds the array in order.
✗ Incorrect
Counting sort creates a count array for each number's frequency, then writes numbers back in sorted order. The input array is sorted as [1, 2, 2, 3, 3, 4, 8].
🧠 Conceptual
intermediateCounting Sort Stability Property
Which statement correctly describes the stability property of counting sort?
Attempts:
2 left
💡 Hint
Stability means equal elements keep their original order after sorting.
✗ Incorrect
Counting sort is stable because it places elements in the output array in the order they appear in the input, preserving relative order of duplicates.
🔧 Debug
advancedIdentify the bug in this counting sort implementation
What error will occur when running this counting sort code on input [3, 1, 2]?
DSA Java
public static void countingSort(int[] arr) { int max = 0; for (int num : arr) { if (num > max) max = num; } int[] count = new int[max + 1]; for (int num : arr) { count[num]++; } int index = 0; for (int i = 0; i < count.length; i++) { while (count[i] > 0) { arr[index++] = i; count[i]--; } } }
Attempts:
2 left
💡 Hint
Check how the count array size is defined compared to max value.
✗ Incorrect
The count array size is max, but indices go up to max, causing out-of-bounds access when num == max.
🚀 Application
advancedCounting Sort with Negative Numbers
How can counting sort be adapted to sort an array containing negative numbers like [-5, -10, 0, -3, 8, 5, -1, 10]?
Attempts:
2 left
💡 Hint
Counting sort needs non-negative indices for counting array.
✗ Incorrect
By shifting all numbers to be non-negative, counting sort can count frequencies correctly. After sorting, shift back to original values.
🧠 Conceptual
expertTime Complexity of Counting Sort
What is the time complexity of counting sort for sorting n elements with maximum value k, and why?
Attempts:
2 left
💡 Hint
Counting sort does not compare elements but uses counting arrays.
✗ Incorrect
Counting sort runs in linear time relative to input size n plus the range k of input values, making it O(n + k).
