Introduction
Count Sort is a non-comparison based sorting algorithm.
Instead of comparing elements, it:
- counts frequency of elements
- reconstructs sorted array using counts
This algorithm works efficiently when:
- range of values is small
This problem helps in understanding:
- frequency arrays
- counting techniques
- non-comparison sorting
- efficient sorting for limited ranges
Example
Input:arr = [4, 2, 2, 8, 3, 3, 1]
Output:
[1, 2, 2, 3, 3, 4, 8]
Explanation: Frequencies are counted and array is rebuilt in sorted order.
Constraints
1 <= arr.length <= 10^50 <= arr[i] <= 10^5
Approach : Frequency Counting
Explanation
Count Sort works in three steps:
- Find maximum element
- Count frequency of every value
- Rebuild sorted array
Unlike comparison-based sorting:
- no swapping is required
Steps
- Find maximum element.
- Create count array.
- Count frequencies.
- Rebuild sorted array.
- Return sorted array.
Dry Run
Input:[4, 2, 2, 8, 3, 3, 1]
Maximum element: 8
Frequency count:
1 → 1
2 → 2
3 → 2
4 → 1
8 → 1
Rebuild array: [1, 2, 2, 3, 3, 4, 8]
Final Result: [1, 2, 2, 3, 3, 4, 8]
Count Sort Code
Complexity Analysis
Time Complexity: O(n + k)Explanation:n elements are counted and k range values are traversed.
Space Complexity: O(k) Explanation:
Extra count array is used.
Edge Cases
- Empty array
- Single element array
- Duplicate elements
- Already sorted array
- Large value ranges
Why This Problem is Important
Count Sort helps in understanding:
- Frequency counting
- Non-comparison sorting
- Counting arrays
- Efficient range-based sorting
- Linear-time sorting concepts
It is one of the most important non-comparison sorting algorithms.
Real-World Applications
Count Sort concepts are used in:
- Frequency analysis
- Exam score sorting
- Age-based grouping
- Histogram processing
- Radix Sort
Common Mistakes
- Incorrect count array size
- Forgetting maximum element
- Wrong rebuilding logic
- Handling large ranges inefficiently
Interview Tips
Interviewers often expect:
- O(n + k) explanation
- Frequency counting understanding
- Difference from comparison sorting
Always explain:
- why comparisons are avoided
- how frequencies help sorting
- when Count Sort is efficient
Related Questions
- Radix Sort
- Bucket Sort
- Heap Sort
- Sort Colors
- Frequency Count
Final Takeaway
Count Sort is a fundamental non-comparison sorting algorithm that teaches frequency counting and range-based sorting techniques. Understanding Count Sort builds a strong foundation for advanced linear-time sorting algorithms and interview problems.