Listing index: O(1) id lookup with filtered ranking

seniorjava · AI-off30:00
  1. 1Clarify
  2. 2Code
  3. 3Test
  4. 4Optimize
  5. 5Done

Problem

Build an in-memory index over home Listing records (id, city, price, beds). getById(id) returns the matching Listing in O(1), or null if absent. search(city, maxPrice) returns the ids of listings in that city priced at or below maxPrice, cheapest first, ties broken by id ascending. Re-adding the same id must update the existing record, not duplicate it.

1Your goal now — Clarify

Restate the problem in one sentence and list the edge cases — before writing any code.

Say your opening out loud to unlock coding

Then keep talking — restate the problem + the edge cases in your own words.

Let me make sure I understand the problem, then I'll walk through my approach.

checking microphone…

Self-check

Hints / what this doesn't test

This is an Opendoor-flavored applied problem: model records and serve two access patterns — a point lookup and a filtered, ranked query. Restate it first — "So getById has to be O(1), and search is a city + price-ceiling filter sorted by price then id, and adding a known id is an upsert?"

What this problem does not test (say so out loud): pagination, multi-field filters (beds, geo radius), full-text matching, and a precomputed sorted index per city are out of scope here — but a senior names that the linear scan in search is the obvious scaling cost and that a per-city price-sorted structure is the next step.

Solution.javaauto-runs ~0.8s after you pause

Tests

○ Not run yet — edit the code or press Run
  • by_id
  • by_id_missing
  • search_filter
  • search_rank
  • + 2 hidden tests — revealed once the visible ones pass
Step 1 of 5: Clarify