Difficulty: Medium, Asked-in: Microsoft, Amazon.
Introduction to linear time sorting
Sorting algorithm that relies on comparisons between elements (like merge sort or quicksort) will take at least O(nlogn) time. This is known as the lower bound for comparison-based sorting algorithms. But it's possible to do better than O(nlogn) under certain conditions. For example, if input is almost sorted, insertion sort can sort it in O(n) time. Similarly, if input only contains 0's, 1's, and 2's, we can sort it in O(n) time.
What is counting sort?
Counting sort is a non-comparison sorting algorithm. Instead of comparing pairs of elements, it counts how many times each value appears, then uses those counts to place the values in sorted order. If the input contains n integers, each in the range from 0 to k, counting sort takes O(n + k) time. When k = O(n), the running time is O(n).
How does counting sort work?
Counting sort uses the indices of the array to determine the correct position of each element in the sorted array. To do this, it first counts the number of elements that are less than a given element x. It then places x in its correct position in the sorted array based on this count. For example, if there are 17 elements less than x, then x belongs in the 18th position in the sorted array.
If input array contains repeated elements, the counting sort needs to be modified slightly. When values are repeated, we want to maintain the stable order of elements in the sorted output, which means that if A[i] == A[j] and i < j, then A[i] should appear before A[j] in the sorted output.
Implementation steps
Step 1
The counting sort uses two additional arrays to sort the input: an array B[n] to store the sorted output and an array C[k+1] to store the count of every unique element in the input.
The size of the count array C[] is k+1 because the range of input values is [0, k]. This means that there are k+1 possible unique elements in the input. By counting the occurrences of each unique element in the input and storing them in C[], the counting sort determine the correct position of each element in the sorted output.
At the start, we initialize all values of C[] to 0's.
Step 2
We first count the occurrences of each unique value in the input array A[] by traversing it from the beginning. For each element A[i], we increment the count at C[A[i]]. By the end of this process, C[A[i]] will contain the number of times the value A[i] appears in A[], where 0 ≤ A[i] ≤ k.
for i from 0 to n - 1
C[A[i]] = C[A[i]] + 1Step 3
At this point, the frequency of each value A[i] is stored in C[]. To determine the position of each value in the sorted output, we update C[] to store the number of elements less than or equal to each value A[i]. We use the following formula: Number of elements less than or equal to A[i] = C[0] + C[1] + ... + C[A[i] - 1] + C[A[i]]. We can calculate these values for all elements in one pass by computing a running sum of C[] from index 0 to k.
for i from 1 to k
C[i] = C[i - 1] + C[i]Step 4
At this point, C[] will be in nondecreasing order, and C[A[i]] will store the number of elements less than or equal to A[i]. If all n elements in A[] are distinct, the correct final index of A[i] in the output array B[] will be C[A[i]] - 1, since there are C[A[i]] elements less than or equal to A[i]. But if A[] contains repeated elements, we need to modify the process slightly to maintain their relative order.
To do this, we traverse A[] from right to left and decrement C[A[i]] each time after placing A[i] into B[]. Decrementing C[A[i]] causes the next element with value A[i] to be placed immediately before the previous one in B[]. This ensures that B[] is correctly sorted and stable, even if A[] contains repeated elements.
for i from n - 1 down to 0
B[C[A[i]] - 1] = A[i]
C[A[i]] = C[A[i]] - 1- By the end of above process, our sorted output will be stored in array B[].
Pseudocode
countingSort(A, B, k, n)
create count array C of size k + 1, initialized to 0
for i from 0 to n - 1
C[A[i]] = C[A[i]] + 1
// Convert frequencies to cumulative counts.
for i from 1 to k
C[i] = C[i - 1] + C[i]
// Place elements into B from right to left to preserve stability.
for i from n - 1 down to 0
B[C[A[i]] - 1] = A[i]
C[A[i]] = C[A[i]] - 1Counting sort visualisation

Time and space complexity analysis
The counting sort algorithm consists of four loops:
- The first loop takes O(k) time.
- The second loop takes O(n) time.
- The third loop takes O(k) time.
- The fourth loop takes O(n) time.
The overall time complexity of the counting sort = O(k) + O(n) + O(k) + O(n) = O(k + n). If k = O(n), the time complexity of the counting sort algorithm becomes O(n).
The space complexity of the counting sort = Size of the output array B[] + Size of the count array C[] = O(n) + O(k) = O(n + k). If k = O(n), the space complexity of the counting sort becomes O(n).
Properties of counting sort
- The time and space complexity of counting sort depend on the range of the input data. It works efficiently if the range is not significantly greater than the number of elements to be sorted. If k = O(n^2), the time and space complexity of counting sort will be O(n^2).
- Counting sort is able to beat the O(nlogn) lower bound of comparison-based sorting algorithms because it does not use comparison operations to sort the input. Instead, it uses the actual values of the elements to determine their correct position in the output.
- The stability property of counting sort is important when additional data are carried around with the elements being sorted. It is also important for another reason: counting sort is often used as a subroutine in the radix sort algorithm, which relies on the stability of counting sort to correctly sort the input.
- Counting sort uses an idea similar to the direct addressing method of hashing.
Critical ideas to think!
There are a few questions to consider when working with the counting sort algorithm:
- How can we extend the counting sort algorithm to work for negative inputs?
- Why do we run the last loop from the right end of the input array A[]?
- Instead of running the last loop from i = n - 1 to 0, could we modify the above implementation by running the loop from i = 0 to n - 1? Would the modified algorithm be stable?
- How do we modify the above algorithm if we want to sort input data given in the range from [a, b]?
- Can you describe an algorithm for the following problem: given n integers in the range 0 to k, preprocess the input and then answer any query about how many n integers fall into a given range [a...b] in O(1) time. The algorithm should use O(n + k) preprocessing time.
Reference: Algorithms by CLRS
Enjoy learning, Enjoy algorithms!
