Age Sort
You started a new job and received your first assignment. You work for a huge e-commerce company that receives millions of orders per day, and they have asked you to create a sorted list of ages associated with each order.
Given a list of ages, write a function sortByAge that returns a sorted list of all the ages in ascending order.
You can reasonably assume the range of ages is 0 to 100.
Breakdown
Approach and test strategy
Counting sort over a bounded integer domain
Read the approach, boundary cases, and complexity
The ages are whole numbers from zero through one hundred. Count occurrences for each allowed age, then emit each age as many times as its count requires. The bounded key range lets the implementation avoid comparing every pair of input values. Keep duplicate ages; a set would lose required output entries.
Cases to check
- Try an empty list and repeated copies of the same age.
- Include the domain endpoints zero and one hundred.
- Compare the result with an ordinary numeric sort while checking that every input occurrence remains present.
Cost model
For n ages and a domain of k allowed ages, counting and reconstruction take O(n + k) time. Counts use O(k) auxiliary storage; the returned output contains n entries. Here k is fixed at 101.
Programming languages for this lesson
Starter code and reference implementations are available in:
The editor shows which of these languages can run on this deployment.
Validate My Answer
A brute force solution would just be to use our native sorting function for O(n log n) time. You can actually do this in O(n) time. Think through constraints on this question that make that possible.
Duplicates of the same age must all appear in the output and be grouped together.
Age Sort
You started a new job and received your first assignment. You work for a huge e-commerce company that receives millions of orders per day, and they have asked you to create a sorted list of ages associated with each order.
Given a list of ages, write a function sortByAge that returns a sorted list of all the ages in ascending order.
You can reasonably assume the range of ages is 0 to 100.