Bestseller shelf
EasyOnline Assessment
Choose which products go on a bestseller shelf, keeping every product that ties for the last spot.
A shop logs its sales as strings "name:qty". The quantity is an integer and is negative when the entry records a return. Product names are matched ignoring leading and trailing spaces and ignoring case: " Tea " and "tea" are the same product, reported in lowercase (spaces inside a name are kept). A product's total is the sum of all of its quantities, returns included.
Only products with a total greater than 0 can be on the shelf. Rank the eligible products by total, highest first. The shelf has room for k products, but ties are never split: if the product in position k shares its total with other products, all of them are included. If fewer than k products are eligible, all eligible products are included.
Input: sales, a list of strings in the format above, and k, a positive integer.
Output: a list of [name, total] pairs for the products on the shelf, sorted by total descending and then by name ascending (lexicographic). If no product is eligible, return [].
Example 1
- Input:
- [["Tea:5","coffee:3","tea:-1","Cocoa:3","mint:1"],2]
- Output:
- [["tea",4],["cocoa",3],["coffee",3]]
- Explanation
- Totals: tea 5 - 1 = 4, coffee 3, cocoa 3, mint 1. The shelf holds 2 products, so the second place total is 3. Everyone with at least 3 makes it, which includes both coffee and cocoa. The tie at 3 is ordered by name.
Example 2
- Input:
- [["Gum:2","gum:-2","Mints:1"],3]
- Output:
- [["mints",1]]
- Explanation
- gum sells 2 and then 2 are returned, so its total is 0 and it does not qualify. Only mints (1) remains, even though the shelf could hold 3.
Example 3
- Input:
- [[" Tea :2","tea:1"," Jam:3"],1]
- Output:
- [["jam",3],["tea",3]]
- Explanation
- After trimming and lowercasing, tea totals 2 + 1 = 3 and jam totals 3. With one slot, the cutoff total is 3 and both products reach it, so both are returned (jam first by name).
Constraints
0 <= sales.length <= 2,0001 <= k <= 50- Each entry is
"name:qty"wherenamehas ASCII letters and spaces only andqtyis an integer between-1,000and1,000(it may have no sign or a leading-)