AlgoViz

House robber

medium 18 min

Pick houses along a street to maximise the money taken, never two neighbours.

See it run

At every house you either take it and jump back two, or skip it and keep the best so far: watch that one choice grow from an exponential tree into a single pass with two variables.

Operations

Take or skip: brute recursion

rob(i) is the most money from houses 0 to i. It tries both choices for house i: skip it and take rob(i - 1), or rob it and take nums[i] + rob(i - 2). Two calls per call grow a tree that solves the same questions again and again.

Step 1 of 9

The question: rob(4)

rob(4)call 1

nums = [2, 7, 9, 3, 1]

Street [2, 7, 9, 3, 1]. rob(4) asks for the most money from houses 0 to 4 without robbing two neighbours. Base cases: rob(-1) = 0 (no houses) and rob(0) = nums[0] = 2 (one house: take it).

Step 1: The question: rob(4)

def rob(nums, i):    """Most money from houses 0..i."""    if i < 0:        return 0                          # no houses left    if i == 0:        return nums[0]                    # one house: take it    skip = rob(nums, i - 1)               # leave house i    take = nums[i] + rob(nums, i - 2)     # rob house i, so its neighbour is off limits    return max(skip, take)
Time
O(2ⁿ), exactly Θ(φⁿ)
Space
O(n) call stack
5 houses
15 calls
20 houses
21,891 calls
40 houses
331,160,281 calls

Say the choice out loud: skip means rob(i - 1), take means nums[i] + rob(i - 2). The recurrence is just the bigger of the two.

In the real world

The same house robber doing real jobs. Pick one and step through it.

Every house is richer than the last. It is tempting to start from the richest end, but the table settles it without guessing.

Step 1 of 3

Base cases: 1, then max(1, 2) = 2

nums

  1. 10
  2. 21i
  3. 32
  4. 43
  5. 54

dp

  1. 10
  2. 21
  3. ·2
  4. ·3
  5. ·4
dp[1] = 2

dp[0] = 1, dp[1] = max(1, 2) = 2.

Step 1: Base cases: 1, then max(1, 2) = 2

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Greedy: grab the richest house first

    critical

    Taking the biggest value and crossing out its neighbours feels right but fails: on [2, 3, 2] greedy takes 3, while houses 0 and 2 give 4. Every house affects its neighbours' options, so you need DP.

    Wrong
    def rob(nums):    nums = nums[:]    total = 0    while any(nums):        i = nums.index(max(nums))      # richest house left        total += nums[i]        for j in (i - 1, i, i + 1):            if 0 <= j < len(nums):                nums[j] = 0    return total                       # [2, 3, 2] gives 3
    Right
    def rob(nums):    prev2, prev1 = 0, 0    for x in nums:        prev2, prev1 = prev1, max(prev1, prev2 + x)    return prev1                       # [2, 3, 2] gives 4
  • Every other house

    critical

    Comparing the sum of even indices with the sum of odd indices misses plans with a gap of two or more. On [2, 1, 1, 2] both give 3, but houses 0 and 3 give 4.

    Wrong
    def rob(nums):    return max(sum(nums[0::2]), sum(nums[1::2]))   # [2, 1, 1, 2] gives 3
    Right
    def rob(nums):    prev2, prev1 = 0, 0    for x in nums:        prev2, prev1 = prev1, max(prev1, prev2 + x)    return prev1                                   # [2, 1, 1, 2] gives 4
  • dp[1] = nums[1]

    major

    dp[1] is the best of the first two houses, not house 1 alone. With dp[1] = nums[1], [7, 2, 1] gives 7 + 1 = 8 by luck but [7, 2] gives 2 instead of 7.

    Wrong
    dp[0] = nums[0]dp[1] = nums[1]                    # forgets that house 0 alone may be better
    Right
    dp[0] = nums[0]dp[1] = max(nums[0], nums[1])      # the richer of the two neighbours
  • Crashing on short streets

    major

    A table version that always writes dp[1] raises IndexError for a single house, and nums[0] raises it for an empty list. Guard both, or use the rolling variables starting at 0, which need no guard.

    Wrong
    def rob(nums):    dp = [0] * len(nums)    dp[0] = nums[0]                    # IndexError on []    dp[1] = max(nums[0], nums[1])      # IndexError on [5]    ...
    Right
    def rob(nums):    if not nums:        return 0    if len(nums) == 1:        return nums[0]    ...                                # or: the rolling version, no guards needed
  • Updating the rolling variables in the wrong order

    major

    Overwriting prev2 before computing the new prev1 means the take option adds x to the wrong value. On [2, 7, 9, 3, 1] it adds every house and returns 22 instead of 12. Use one tuple assignment, or a temporary.

    Wrong
    for x in nums:    prev2 = prev1    prev1 = max(prev1, prev2 + x)     # prev2 is already the new value
    Right
    for x in nums:    prev2, prev1 = prev1, max(prev1, prev2 + x)   # right side uses the old values
  • Circular street: one pass, or no single-house guard

    minor

    Running the straight version on a circular street can rob both the first and last house. Splitting into nums[1:] and nums[:-1] fixes that, but for one house both slices are empty and the answer would be 0 instead of nums[0].

    Wrong
    def rob_circle(nums):    return max(rob_line(nums[1:]), rob_line(nums[:-1]))   # [5] gives 0
    Right
    def rob_circle(nums):    if len(nums) == 1:        return nums[0]    return max(rob_line(nums[1:]), rob_line(nums[:-1]))

Interview tips

  • How to explain it

    • Define dp[i] as the most money from houses 0 to i.
    • For house i: skip it (dp[i - 1]) or take it (nums[i] + dp[i - 2]); dp[i] is the bigger.
    • Base cases dp[0] = nums[0], dp[1] = max(nums[0], nums[1]); answer dp[n - 1].
    • Only two previous values are read, so two variables give O(n) time and O(1) space.
  • Spot it in problems

    • Pick items from a line to maximise a total, and picking one blocks its neighbours.
    • Schedules with a rest or cooldown after each chosen slot.
    • Delete and Earn: bucket the values, then it is house robber on the buckets.
    • Houses in a circle (House Robber II) or on a binary tree (House Robber III).
  • Memory tricks

    • TAKE or LEAVE: Take = nums[i] + dp[i - 2], Leave = dp[i - 1], then MAX.
    • Fibonacci with a max: same two-back shape, max instead of plus.
    • Example to know cold: [2, 7, 9, 3, 1] gives 12 (houses 0, 2, 4); in a circle it gives 11.
  • Watch out

    • dp[1] is max(nums[0], nums[1]), not nums[1].
    • Handle the empty street and a single house.
    • Update prev2 and prev1 together.
    • Circular version: one house returns nums[0] before slicing.