Counting Sort (Implementation)
Non-Comparison Sorting / Frequency MappingSolved Nov 19, 2025
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 130 pointsSolved (Medium) 0/40Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Watch the concept video if the pattern is new to you.
Step 2
Try it on paper
5–10 minutes, no code yet
ProblemProblem statementGiven an array of integers where the range of values is known and relatively small, sort the array using the Counting Sort algorithm.ReadHide
Problem Description
Given an array of integers where the range of values is known and relatively small, sort the array using the Counting Sort algorithm.
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Count the occurrences of each unique element in the input. Use these counts to determine the position of each element in the output array. This effectively bypasses the O(N log N) limit of comparison sorts.
Approaches
1. Frequency Array Mapping (Optimal) - O(N + K) ⭐
Idea: Counting sort works by:
- Finding the maximum element in the array to define the range
K. - Creating a frequency (count) array of size
K+1. - Storing the count of each element.
- (Optional for stability) Modifying the count array to store the cumulative sum of counts.
- Placing elements into a new output array based on their cumulative counts and decrementing the count.
Constraints: * This algorithm is highly efficient only when K (the range of elements) is not significantly larger than N (the number of elements).
- Traditional implementation handles only non-negative integers (though it can be adapted for negatives by using an offset).
Solution code
from typing import List
class Solution:
# Optimized: O(N + K) Time, O(N + K) Space
def countingSort(self, nums: List[int]) -> List[int]:
if not nums:
return nums
# 1. Find the range (handling negative numbers with an offset)
min_val = min(nums)
max_val = max(nums)
range_of_elements = max_val - min_val + 1
# 2. Initialize the count array
count = [0] * range_of_elements
output = [0] * len(nums)
# 3. Store the frequency of each element
for num in nums:
count[num - min_val] += 1
# 4. Modify count[i] to contain the actual position in output
for i in range(1, len(count)):
count[i] += count[i - 1]
# 5. Build the output array (traverse backwards for stability)
for i in range(len(nums) - 1, -1, -1):
output[count[nums[i] - min_val] - 1] = nums[i]
count[nums[i] - min_val] -= 1
return outputOther ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language