← Questions

Rearrange house numbers into sorted, duplicate-free neighborhoods

0
GoogleCoding

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:

  1. Every neighborhood keeps its original size (the number of houses in it does not change).
  2. No neighborhood holds the same house number twice.
  3. 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 c copies into c different 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) for K neighborhoods.
  • 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 t times per neighborhood.
  • Return how many valid arrangements exist.

Where it's asked

What it tests

greedy · heap · counting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding