Paginate Search Results by Unique Host
Problem statement
Search results are supplied in descending score order. Each element of results is the original CSV string host_id,listing_id,score,city; the host ID is the substring before the first comma.
Partition the results into pages containing at most resultsPerPage entries. To build each page:
- Scan the remaining results in order and select the earliest entry from each host not yet represented on this page, until the page is full or the scan ends.
- If the page is still not full, append the earliest remaining skipped entries in their current order until the page is full or no results remain.
- Remove every selected entry, then build the next page from the remaining list.
Return every selected original CSV string in page order. Insert an empty string between consecutive pages, but not after the final page.
Function
paginate(resultsPerPage: int, results: String[]) → String[]Examples
Example 1
resultsPerPage = 5results = ["1,28,300.6,San Francisco","4,5,209.1,San Francisco","20,7,203.4,Oakland","6,8,202.9,San Francisco","6,10,199.8,San Francisco","1,16,190.5,San Francisco","6,29,185.3,San Francisco","7,20,180.0,Oakland","6,21,162.2,San Francisco","2,18,161.7,San Jose","2,30,149.8,San Jose","3,76,146.7,San Francisco","2,14,141.8,San Jose"]return = ["1,28,300.6,San Francisco","4,5,209.1,San Francisco","20,7,203.4,Oakland","6,8,202.9,San Francisco","7,20,180.0,Oakland","","6,10,199.8,San Francisco","1,16,190.5,San Francisco","2,18,161.7,San Jose","3,76,146.7,San Francisco","6,29,185.3,San Francisco","","6,21,162.2,San Francisco","2,30,149.8,San Jose","2,14,141.8,San Jose"]The first page takes the earliest entries from hosts 1, 4, 20, 6, and 7. On page two, host 6 appears first, so its later result is skipped during the unique-host scan and then used to pad that page.
Example 2
resultsPerPage = 3results = ["1,10,9.0,A","1,11,8.0,A","2,20,7.0,B","1,12,6.0,A"]return = ["1,10,9.0,A","2,20,7.0,B","1,11,8.0,A","","1,12,6.0,A"]The unique-host scan selects hosts 1 and 2. It cannot find a third distinct host, so the earliest skipped host-1 result pads the first page.
Example 3
resultsPerPage = 2results = ["1,1,3.0,A","2,2,2.0,B","3,3,1.0,C"]return = ["1,1,3.0,A","2,2,2.0,B","","3,3,1.0,C"]All hosts are distinct, so each page simply takes the next entries in order. The last page has one result and no trailing separator.
Constraints
1 <= resultsPerPage <= 1000.0 <= results.length <= 1000.- Every result is a valid CSV string with exactly four fields: integer host ID, integer listing ID, finite decimal score, and a non-empty city containing no comma.
resultsis already sorted by non-increasing score.