Model answer
Counting n input keys is O(n), scanning k possible key values or prefix counts is O(k), and placing n outputs is O(n). These sequential stages add to O(n+k).
Use the key terms, then explain the reasoning.
Counting sort counts occurrences of integer keys in a bounded range, avoiding comparison sorting entirely.
Counting sort replaces comparisons with direct addressing. A frequency array indexed by key records occurrences; prefix sums then reveal where each key's output block ends.
Stable construction scans input from right to left, decrements the key's cumulative count, and places the record at that position. The method is attractive only when key range k is reasonable relative to n.
Count bounded keys
| Operation | Best | Average | Worst | Extra space |
|---|---|---|---|---|
| Sort | O(n+k) | O(n+k) | O(n+k) | O(n+k) |
Prefix sums convert frequencies into final positions. Iterating backward preserves stability.
Open a prompt when you are ready to check your answer.