Skip to the solution
MediumDSA13 min read

How do you solve the house robber problem?

494 views

The problem

Question presented to candidate: "You are a robber on a street of houses, each with some amount of money. Robbing two adjacent houses triggers the alarm. Given the amounts, return the most money you can rob tonight. Please write it in Python. If you finish early: what if the street is a circle?"

What a strong answer should cover:

  • The take-or-skip recurrence best[i] = max(best[i - 1], best[i - 2] + nums[i]), with base cases for zero and one house.
  • Why "every other house" and other greedy rules fail ([2, 1, 1, 2] β†’ 4, not 3).
  • O(n) time with O(1) space via two rolling variables; the full table only when the chosen houses must be returned.
  • The circular variant: max of two line problems, excluding the first or the last house.
  • Python specifics: the one-line tuple shift prev, cur = cur, max(cur, prev + x), and that dp[-1] silently reads the last element instead of failing.

Clarifying questions expected:

  • "Is the street a line or a circle?"
  • "Do you want the maximum amount only, or also which houses?"
  • "Can amounts be zero or negative, and how large can the total get?"

Code / implementation expected: Yes β€” an O(n), O(1)-space Python function; reconstruction or the circular version as follow-ups.

  • dp

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read Β· 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonHouse robber with the robbed houses recovered, against the every-other-house guess
PythonThe circular street (House Robber II) and a brute-force check on 300 random streets

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 87 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the word break problem?

Continue