Rearrange house numbers into sorted, duplicate-free neighborhoods
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Google. It tests greedy, heap and counting.
A city is a list of neighborhoods. Each neighborhood is a list of house numbers (integers), and numbers may repeat, both within a neighborhood and across the city.
Move houses between neighborhoods so that:
- Every neighborhood keeps its original size (the number of houses in it does not change).
- No neighborhood holds the same house number twice.
- Each neighborhood is listed in ascending order.
The city as a whole must keep exactly the same house numbers with the same counts. You only move houses; you never add, remove or renumber them.
Implement:
def rearrange_houses(houses: list[list[int]]) -> list[list[int]]:
...
Return any arrangement that meets all three rules, or [] if none exists. Empty neighborhoods are allowed and must stay empty.
Constraints
0 <= len(houses) <= 10^5- Total number of houses
N <= 2 * 10^5 - House numbers fit in a 32-bit signed integer.
Example 1
Input: [[4, 4, 7], [2, 4], [7, 2, 9]]
Output: [[2, 4, 7], [4, 7], [2, 4, 9]] (one valid answer)
Sizes stay 3, 2, 3. The three 4s, two 7s and two 2s each land in different neighborhoods.
Example 2
Input: [[1, 1, 2], [2]]
Output: []
The first neighborhood needs three different numbers, but the city only has two distinct numbers (1 and 2).
Clarifying questions
- Is any valid arrangement acceptable, or is a specific one expected?
- Does the output keep the neighborhoods in the input order, each with its original size?
- Is an empty city answered with
[], and is that distinguishable from "impossible"? - Can a neighborhood be empty in the input?
What a strong answer covers
- Reduces the problem to placing each number's
ccopies intocdifferent neighborhoods without exceeding any neighborhood's size. - States the necessary checks, such as a number's count never exceeding the number of non-empty neighborhoods.
- Uses a greedy: take numbers by count, highest first, and put the copies of each into the neighborhoods with the most free space left (a max-heap of remaining sizes); argues why this order never blocks a later number.
- Sorts each neighborhood at the end.
O(N log K)forKneighborhoods. - Tests both examples, one neighborhood holding everything, and many copies of one number.
Follow-ups
- Minimise the number of houses that move.
- Allow a number at most
ttimes per neighborhood. - Return how many valid arrangements exist.
Where it's asked
What it tests
greedy · heap · counting
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
