Counting Sort Algorithm in DSA C# - Time & Space Complexity
Counting Sort is a special sorting method that works well when numbers are in a small range.
We want to know how the time it takes changes as the list size and number range grow.
Analyze the time complexity of the following code snippet.
public static void CountingSort(int[] arr, int maxValue) {
int[] count = new int[maxValue + 1];
foreach (int num in arr) {
count[num]++;
}
int index = 0;
for (int i = 0; i < count.Length; i++) {
while (count[i]-- > 0) {
arr[index++] = i;
}
}
}
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 | 50 | About 100 + 50 = 150 operations |
| 1000 | 100 | About 1000 + 100 = 1100 operations |
Pattern observation: The time grows roughly by adding the input size and the range size, not multiplying them.
Time Complexity: O(n + k)
This means the time grows linearly with 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: The time depends on both the number of items and the range size; if the range is very large, the algorithm slows down.
Understanding Counting Sort's time helps you choose the right sorting method based on data size and range, a key skill in coding challenges and real projects.
"What if the input array contains negative numbers? How would the time complexity change if we adjust Counting Sort to handle them?"
Practice
Counting Sort Algorithm?Solution
Step 1: Understand Counting Sort principle
Counting sort counts how many times each value appears in the input.Step 2: Use counts to place elements
These counts help to directly place elements in the sorted output without comparisons.Final Answer:
Count the occurrences of each element and use counts to place elements in order -> Option AQuick Check:
Counting occurrences = A [OK]
- Thinking counting sort compares elements
- Confusing counting sort with merge sort
- Assuming counting sort works on all data types
Solution
Step 1: Determine size of count array
For range 0 to 9, we need 10 slots to count each number.Step 2: Correct C# syntax for array declaration
Useint[] count = new int[10];to create an array of size 10.Final Answer:
int[] count = new int[10]; -> Option BQuick Check:
Array size = max value + 1 = 10 [OK]
- Using size less than max value + 1
- Declaring count as single int instead of array
- Using incorrect array size causing index errors
int[] arr = {4, 2, 2, 8, 3, 3, 1}?
int max = 8;
int[] count = new int[max + 1];
int[] output = new int[arr.Length];
// Count occurrences
foreach (int num in arr) count[num]++;
// Modify count array
for (int i = 1; i <= max; i++) count[i] += count[i - 1];
// Build output
for (int i = arr.Length - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
// Print output
foreach (int num in output) Console.Write(num + " ");Solution
Step 1: Count occurrences of each number
Count array after counting: [0,1,2,2,1,0,0,0,1]Step 2: Modify count array to cumulative counts
Cumulative count: [0,1,3,5,6,6,6,6,7]Step 3: Place elements in output using counts
Placing elements from right to left gives sorted array: 1 2 2 3 3 4 8Final Answer:
1 2 2 3 3 4 8 -> Option AQuick Check:
Sorted array = 1 2 2 3 3 4 8 [OK]
- Not using cumulative counts before placing elements
- Placing elements from left to right causing wrong order
- Off-by-one errors in indexing output
int max = 5;
int[] count = new int[max];
int[] arr = {1, 4, 3, 2, 5};
foreach (int num in arr) {
count[num]++;
}Solution
Step 1: Analyze count array size
Count array size is 5, but max value is 5, so index 5 is out of range.Step 2: Fix by increasing count array size
Count array should be size max + 1 = 6 to include index 5 safely.Final Answer:
Change count array size to max + 1 to avoid index out of range -> Option CQuick Check:
Array size = max + 1 to cover all indices [OK]
- Using count array size equal to max value only
- Ignoring index out of range exceptions
- Assuming default array size is enough
int[] arr = {5, 3, 0, 2, 3, 5, 1, 4} and want to sort it using counting sort. However, the array may contain negative numbers in future. How should you modify the counting sort algorithm to handle negative numbers correctly?Solution
Step 1: Identify problem with negative numbers
Counting sort uses array indices as counts, negative indices are invalid.Step 2: Shift numbers to non-negative range
Add absolute value of minimum negative number to all elements to make them non-negative.Step 3: Apply counting sort on shifted values
Sort shifted values, then shift back to original values after sorting.Final Answer:
Shift all numbers by adding the absolute value of the minimum negative number before counting -> Option DQuick Check:
Shift negatives to zero or above before counting [OK]
- Trying to use negative indices in count array
- Ignoring negative values in input
- Using dictionary without sorting logic
Ready to prove it?
Pass the test and this pattern moves unknown
