Bank app~15 min2s · 256 MBtarget O(n) time, O(1) spacesorting
A bank branch keeps a list of its savings accounts with the balance of each, in units. The branch dashboard shows only the podium: the three highest balances, from the highest to the lowest.
Two accounts can hold the same balance, and then the balance appears twice on the podium. Your team lead asks you to compute the podium.
Write podium(balances).
balances[i] is the balance of account i, in units. There are at least three accounts.Input: balances = [40, 90, 70, 90, 10]
Output: [90, 90, 70]The balances are 40, 90, 70, 90 and 10. Sorted from high to low they are 90, 90, 70, 40, 10, so the podium is the first three. The three places are kept in order while the list is read.
| Balance read | First | Second | Third |
|---|---|---|---|
| (start) | empty | empty | empty |
| 40 | 40 | empty | empty |
| 90 | 90 | 40 | empty |
| 70 | 90 | 70 | 40 |
| 90 | 90 | 90 | 70 |
| 10 | 90 | 90 | 70 |
The answer is [90, 90, 70].
Input: balances = [5, 6, 7]
Output: [7, 6, 5]Three accounts: the podium is all three, from high to low.
Input: balances = [0, 0, 0, 0]
Output: [0, 0, 0]All balances are 0. An empty account with balance 0 is an account like any other, so the podium is 0, 0, 0.
3 ≤ length of balances ≤ 10^50 ≤ balances[i] ≤ 10^6A list of 100,000 accounts needs about 5 x 10^9 comparisons if you sort all of it with selection sort. That is too slow.
You need only three values, so sorting the other accounts is wasted work. Keep three variables in order and read the list once.