Airbnb questions

Paginate Search Listings

AirbnbPhone screenMedium

A search returns listings ordered from best to worst score. Each listing is a pair [listing_id, host_id]. A page shows page_size listings, and the same host should not appear twice on one page when that can be avoided.

Part 1: Spread hosts across pages

Given a list of listings ordered from best to worst score, where each listing is [listing_id, host_id], split it into pages and return each page as a list of listing ids.

Build the pages one at a time from the listings not yet shown, in order from best score. For one page, scan the remaining listings from the best and take each one whose host is not already on the page, until the page is full. If the scan ends with the page not full, fill the remaining slots with the earliest unused listings in their original order, even if their host is already on the page. A page lists the scan picks first, then the fillers. Listings not taken stay in their original order for the next page. The last page may be shorter than page_size.

  1. Example 1
    listings
    [[1,1],[2,1],[3,2],[4,3],[5,2],[6,1],[7,4],[8,5]]
    page_size
    3
    Output
    [[1,3,4],[2,5,7],[6,8]]

    Why: Page 1 scans listings 1 to 8 and takes 1 (host 1), skips 2 (host 1 again), then takes 3 (host 2) and 4 (host 3), giving [1, 3, 4]. Page 2 starts from the remaining 2, 5, 6, 7, 8 and takes 2 (host 1), 5 (host 2), 7 (host 4), giving [2, 5, 7]. Page 3 holds the last two listings, 6 and 8, whose hosts differ.

Constraints

  • 1 <= len(listings) <= 10^4
  • 1 <= page_size <= 10^4
  • 1 <= listing_id, host_id <= 10^9
  • listing_id values are distinct
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Paginate Search Listings: Airbnb interview question | LoopCoach