Monitoring~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1636sorting
A monitoring system receives a stream of alerts, and each alert carries an error code. The on-call dashboard lists each different code once, with the most frequent code at the top.
When two codes occur equally often, the code that appeared first in the stream comes first. Your team lead says: "The counts are whole numbers between 1 and the number of alerts, so you may not need a comparison sort at all."
Write order_error_codes(codes).
codes lists the alert codes in the order the alerts arrived.codes: the code that appeared earlier comes first.Input: codes = [404, 500, 404, 301, 500, 404, 200]
Output: [404, 500, 301, 200]Code 404 occurs 3 times and code 500 occurs 2 times. Codes 301 and 200 occur once each. Code 301 appeared before 200, so it comes first.
| Code | Count | First appearance |
|---|---|---|
| 404 | 3 | 0 |
| 500 | 2 | 1 |
| 301 | 1 | 3 |
| 200 | 1 | 6 |
Input: codes = []
Output: []There are no alerts, so the answer is an empty list.
Input: codes = [7, 8, 8, 7]
Output: [7, 8]Both codes occur twice. Code 7 appeared first.
0 ≤ codes.length ≤ 100,000 (alerts)0 ≤ codes[i] ≤ 1,000,000,000 (error code)Counting each distinct code by scanning the list costs about n × d steps, up to 10^10 when every code is different. A hash map counts all codes in n steps. The counts are whole numbers from 1 to n, so a bucket for each count orders them in about n more steps.