PPractick

DSA interview question

House Robber

Medium · Algorithms · Topics: dynamic programming

The problem

You're a professional (fictional, of course) burglar planning a heist along a single street of houses. Each house has a certain amount of money stashed inside. The catch: if you rob two adjacent houses on the same night, their connected security systems will trigger and alert the police. Your task: given the amount of money in each house, determine the maximum amount you can rob without ever robbing two adjacent houses.

Example: houses with money [1, 2, 3, 1] → rob house 0 and house 2 → 1 + 3 = 4.

Function signature

int rob(vector<int>& nums);

Test cases

Input numsOutputExplanation
[1,2,3,1]4Rob houses 0 and 2 → 1+3=4
[2,7,9,3,1]12Rob houses 0, 2, 4 → 2+9+1=12
[]0No houses, nothing to rob
[5]5Single house, rob it
[5,1]5Two houses, rob the bigger one
[2,1,1,2]4Rob houses 0 and 3 → 2+2=4
[10,10,10,10,10]30Rob houses 0, 2, 4 → 10+10+10=30

(Confirm: array can be empty; amounts are non-negative integers.)

How interviewers phrase it

Clarifying questions to ask

  1. Can the array be empty, and if so, what should the result be? (0, trivially.)
  2. Are all amounts non-negative, or could there be negative values (which would mean sometimes robbing nothing is better than robbing a negative-value house)?
  3. Is "adjacent" strictly meaning consecutive indices in the array (i.e., linear street), or could the houses be arranged in a circle (first and last house also adjacent)? Confirm it's linear for this version.
  4. Do you want just the maximum amount, or also which houses were robbed?

Follow-ups to expect

  1. "What if the houses are arranged in a circle (first and last are also adjacent)?"
  2. "Can you solve this with O(1) space instead of O(n)?"
  3. "What if houses are arranged in a binary tree instead of a line (House Robber III)?"
  4. "Can you also return which houses were robbed, not just the total?"
  5. "What if you could rob at most k houses total (not necessarily maximizing money alone), or there's a limit on non-adjacent picks?"
  6. "What's the recurrence relation and can you explain why greedy doesn't work here?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in