Social feed~10 min2s · 256 MBtarget O(n) time, O(n) spacesorting
A social app shows a feed of posts, and each post has an age in whole days: 0 for today, up to 365 for a year old. A moderation screen lists the ages of the day's reported posts from the youngest to the oldest.
The list can hold 100,000 ages, and the screen refreshes often. Your team lead says: "Every age is a whole number from 0 to 365, so you do not need to compare ages with each other."
Write sort_ages(ages).
Input: ages = [30, 2, 365, 2, 0, 30]
Output: [0, 2, 2, 30, 30, 365]Six ages and 366 possible values. Only four values occur.
| Age | How many posts |
|---|---|
| 0 | 1 |
| 2 | 2 |
| 30 | 2 |
| 365 | 1 |
Writing each age out as often as it was counted gives 0, 2, 2, 30, 30, 365.
Input: ages = []
Output: []There are no posts, so the answer is an empty list.
Input: ages = [7, 7, 7]
Output: [7, 7, 7]Three equal ages stay as they are.
0 ≤ ages.length ≤ 100,000 (reported posts)0 ≤ ages[i] ≤ 365 (age in whole days)Comparing every pair costs about n × n / 2 steps: 4,999,950,000 at n = 100,000. Counting the ages costs about 2n + 366 = 200,366 steps, because there are only 366 possible ages.