DSA
    intermediate

    Counting Sort

    Software Engineer path · lesson 14 of 99
    time O(n+k)
    space O(n+k)

    Whole numbers 0–20. Counting sort pays for the range k, so try Wide range and watch the count array grow.

    Try:
    input40212283343516
    count000102030405060708
    output0123456
    ReadingPrevious totalWrittenFinal

    Values range 0..8, so make 9 counters. No comparisons at all.

    Code (running line highlighted)
    1. 1count = [0] * (k+1)
    2. 2for x in a: count[x] += 1
    3. 3for v in 1..k: count[v] += count[v-1] # end positions
    4. 4for x in reversed(a): # reversed keeps it stable
    5. 5 count[x] -= 1
    6. 6 out[count[x]] = x
    Reads
    0 / 14
    Writes
    0 / 22

    Tap any element in the diagram to inspect its state at this step.

    1 / 24

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    Sort without comparing

    Sequence

    Order the steps of a stable counting sort.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    When is Counting Sort most efficient?

    The short version

    Imagine sorting a deck of cards by suit. Instead of comparing cards, you count how many of each suit you have, then deal them out in order. No comparisons needed!

    In more depth

    Three Phases

    1. Count Phase: Count occurrences of each value

    2. Cumulative Phase: Convert counts to positions

    3. Output Phase: Place elements in correct positions

    Stability

    Iterating backwards during output phase ensures stability (equal elements maintain relative order).

    Limitations

    Only works for discrete values (integers)
    Space increases with range (k)
    Not suitable when k >> n

    When to reach for this

    • Values are integers in a known, limited range
    • Need linear O(n) sorting
    • Sorting characters, grades, or small integers
    • As a subroutine in Radix Sort

    Interview Questions

    Amazon
    Twitter
    Google
    Facebook
    LinkedIn
    Apple
    Google
    Bloomberg

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required