15% off all plans & roadmaps Use code

See plans

House Robber II

Updated

TL;DR: Houses sit in a circle, so the first and last are neighbors and you cannot rob both. Run the linear House Robber DP twice, once without the last house and once without the first, and take the larger result.

Problem

You are a professional robber planning to rob houses along a street. Each house holds a certain amount of money. The houses are arranged in a circle, so the first house is a neighbor of the last one. Adjacent houses share a security system that calls the police if two adjacent houses are broken into on the same night.

Given an integer array nums where nums[i] is the money in house i, return the maximum amount you can rob tonight without alerting the police.

Example 1

Input: nums = [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then house 3 (money = 2), because they are adjacent.

Example 2

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then house 3 (money = 3). The total is 1 + 3 = 4.

Example 3

Input: nums = [1,2,3]
Output: 3

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 1000

Constraints that matter

  • nums.length is at most 100, so even an O(n^2) solution is instant. An O(2^n) search is not: 2^100 is far beyond any time limit.
  • nums.length can be 1. The ranges 0..n-2 and 1..n-1 are both empty or invalid there, so that case needs its own return.
  • nums[i] is never negative, so robbing a house never lowers your total. That lets the recurrence compare only two options per house: take it or skip it.
  • The maximum total is at most 100 * 1000 = 100000, which fits in a 32-bit int in every language. No overflow handling is needed.
  • Only the circle is new compared with the linear problem. The first and last houses are the only extra adjacent pair, which makes a clean reduction possible.

View on LeetCode

Hints

Hint 1

This is a 1D dynamic programming problem in the Fibonacci style.

Hint 2

Split the circle into the two rows, then solve each row without any clever recurrence.

Solution

Intuition

This is a 1D dynamic programming problem in the Fibonacci style. The best total up to house i depends only on the best totals up to i-1 and i-2. Either you skip house i and keep the best up to i-1, or you rob it and add the best up to i-2.

Picture a running tally kept on two sticky notes, not a full ledger. The older note holds prev2 and the newer holds prev1, and each house overwrites the older note with the new total.

The circle adds exactly one new rule: houses 0 and n-1 are neighbors, so a plan cannot contain both. Every valid plan therefore falls in at least one of two groups. Either it never touches the last house, or it never touches the first house.

Each group is a plain row of houses with no wrap-around. The first group is nums[0..n-2] and the second is nums[1..n-1]. You solve each row with the linear recurrence and return the larger answer.

This works because the two groups cover every valid plan, and no plan in either group breaks the circle rule. A plan that skips both ends is counted twice, which is harmless when you take a maximum. The only special input is a single house, where there is no neighbor to conflict with.

Watch the pattern animation

Worked example

Input: nums = [6, 7, 1, 30, 8, 2, 4]
Output: 41
Explanation: Rob the houses holding 7, 30 and 4 (indices 1, 3 and 6). None are adjacent, and index 6 is not next to index 1 in the circle. The total is 7 + 30 + 4 = 41. Taking index 0 instead caps you at 39, because index 6 is then off limits.

Approach 1: Brute force: try every previous house

Split the circle into the two rows, then solve each row without any clever recurrence. For every house k in the row, ask which earlier house you robbed last. That earlier house must be at least two positions back, so you scan all of them and take the best.

This avoids the exponential recursion that tries every subset. A subset search runs about 2^n paths, and 2^100 is hopeless. Here you store the best total ending at each house in a table, so each house is solved once. The scan over earlier houses is the repeated work the next approach removes.

Steps

  1. If there is only one house, return nums[0].
  2. Write a helper solve(lo, hi) that handles the row nums[lo..hi].
  3. In the helper, for each k from lo to hi, set prev to the largest dp[j] over all j from lo to k-2, or 0 if there is none.
  4. Set dp[k] = nums[k] + prev, meaning the best total whose last robbed house is k.
  5. Track the largest dp[k] seen and return it as the row's answer.
  6. Return the maximum of solve(0, n-2) and solve(1, n-1).

Dry run

Example: [6, 7, 1, 30, 8, 2, 4], n = 7.

Row A is indices 0..5. Then dp[0]=6, dp[1]=7, dp[2]=1+6=7, dp[3]=30+max(6,7)=37, dp[4]=8+max(6,7,7)=15, dp[5]=2+max(6,7,7,37)=39. The best for row A is 39.

Row B is indices 1..6. Then dp[1]=7, dp[2]=1, dp[3]=30+7=37, dp[4]=8+max(7,1)=15, dp[5]=2+max(7,1,37)=39, dp[6]=4+max(7,1,37,15)=41. The best for row B is 41.

The answer is max(39, 41) = 41.

Complexity

TimeO(n^2)
SpaceO(n)

Let n be the number of houses. Each row has at most n-1 houses, and for each house the inner loop scans at most n-1 earlier ones. A row costs O(n^2), and two rows cost O(n^2) in total. The dp array holds one value per house, which is O(n) space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def rob(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 1:
            return nums[0]

        def solve(lo: int, hi: int) -> int:
            dp = [0] * n
            best = 0
            for k in range(lo, hi + 1):
                prev = 0
                # any earlier house at least two positions back
                for j in range(lo, k - 1):
                    prev = max(prev, dp[j])
                dp[k] = nums[k] + prev
                best = max(best, dp[k])
            return best

        return max(solve(0, n - 2), solve(1, n - 1))

Approach 2: Two rows with a DP array

What's slow: the inner loop rescans every earlier house for each k. Most of that scan repeats work. The best total over dp[lo..k-2] is the prefix maximum you computed one step ago, plus at most one new entry.

The insight that fixes it: change what dp[i] means. Let it be the best total using only the first i houses of the row, whether or not house i itself is robbed. Then the answer is a max of two numbers, dp[i-1] (skip this house) or dp[i-2] + nums[i] (rob it). The prefix maximum is built into the definition, so no scan is needed.

Steps

  1. If there is only one house, return nums[0].
  2. Write solve(lo, hi) for the row nums[lo..hi] with length m = hi - lo + 1.
  3. Create dp of size m + 1 with dp[0] = 0 and dp[1] = nums[lo].
  4. For i from 2 to m, set dp[i] = max(dp[i-1], dp[i-2] + nums[lo + i - 1]).
  5. Return dp[m] for the row.
  6. Return the maximum of solve(0, n-2) and solve(1, n-1).

Dry run

Example: [6, 7, 1, 30, 8, 2, 4].

Row A is [6, 7, 1, 30, 8, 2]. The table is dp = [0, 6, 7, 7, 37, 37, 39], so row A gives 39.

Row B is [7, 1, 30, 8, 2, 4]. The table is dp = [0, 7, 7, 37, 37, 39, 41]. For instance dp[3] = max(7, 7 + 30) = 37 and dp[6] = max(39, 37 + 4) = 41. Row B gives 41.

The answer is max(39, 41) = 41.

Complexity

TimeO(n)
SpaceO(n)

Let n be the number of houses. Each row fills at most n-1 table cells, and each cell is one max of two earlier cells, which is constant work. Two rows cost about 2n operations, so time is O(n). Each row allocates a table of at most n entries, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def rob(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 1:
            return nums[0]

        def solve(lo: int, hi: int) -> int:
            m = hi - lo + 1
            dp = [0] * (m + 1)
            dp[1] = nums[lo]
            for i in range(2, m + 1):
                # skip house i, or rob it and add the best from i-2
                dp[i] = max(dp[i - 1], dp[i - 2] + nums[lo + i - 1])
            return dp[m]

        return max(solve(0, n - 2), solve(1, n - 1))
1D Array (Fibonacci Style) pattern infographic for House Robber II

Solution pattern

1D Array (Fibonacci Style)

Part of Dynamic Programming (DP) Patterns

Approach 3: Two rows with two rolling variablesOptimal1D Array (Fibonacci Style)

What's slow: the table. The recurrence reads only dp[i-1] and dp[i-2], yet you store the whole history. Every older cell is dead weight after two steps.

The insight that fixes it: keep only two numbers, prev2 for the best two houses back and prev1 for the best one house back. At each house compute cur = max(prev1, prev2 + nums[i]), then slide the pair forward. Run this over nums[0..n-2] and again over nums[1..n-1], and return the larger result. The time stays linear and the extra space drops to a constant.

Steps

  1. If there is only one house, return nums[0].
  2. Write solve(lo, hi) with prev2 = 0 and prev1 = 0.
  3. For each i from lo to hi, compute cur = max(prev1, prev2 + nums[i]).
  4. Shift the window: prev2 = prev1, then prev1 = cur.
  5. After the loop, return prev1 as the best total for the row.
  6. Return the maximum of solve(0, n-2) and solve(1, n-1).

Dry run

Example: [6, 7, 1, 30, 8, 2, 4], n = 7. Each row starts with prev2 = 0 and prev1 = 0.

Row A, indices 0..5 (skips the last house)

inums[i]cur = max(prev1, prev2 + nums[i])prev2 afterprev1 after
06max(0, 0 + 6) = 606
17max(6, 0 + 7) = 767
21max(7, 6 + 1) = 777
330max(7, 7 + 30) = 37737
48max(37, 7 + 8) = 373737
52max(37, 37 + 2) = 393739

Row A returns 39.

Row B, indices 1..6 (skips the first house)

inums[i]cur = max(prev1, prev2 + nums[i])prev2 afterprev1 after
17max(0, 0 + 7) = 707
21max(7, 0 + 1) = 777
330max(7, 7 + 30) = 37737
48max(37, 7 + 8) = 373737
52max(37, 37 + 2) = 393739
64max(39, 37 + 4) = 413941

Row B returns 41. The final answer is max(39, 41) = 41.

Complexity

TimeO(n)
SpaceO(1)

Let n be the number of houses. Each row visits at most n-1 houses and does one addition and two comparisons at each. Two rows cost about 2n steps, which is O(n). The only state is prev1, prev2 and cur, three integers regardless of n, so space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def rob(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 1:
            return nums[0]

        def solve(lo: int, hi: int) -> int:
            prev2, prev1 = 0, 0
            for i in range(lo, hi + 1):
                cur = max(prev1, prev2 + nums[i])
                prev2 = prev1
                prev1 = cur
            return prev1

        # skip the last house, or skip the first house
        return max(solve(0, n - 2), solve(1, n - 1))

Common mistakes

  • Running one linear pass over the whole array with solve(0, n-1). That ignores the circle and can rob both ends. Run two passes, 0..n-2 and 1..n-1, and take the max.
  • Dropping the single-house guard. With n == 1 the ranges 0..-1 and 1..0 are empty, so the answer comes out 0 instead of nums[0]. Add if n == 1: return nums[0] before the two passes.
  • Off-by-one range bounds such as range(0, n - 2) in Python. The end index is exclusive there, so the second-to-last house is dropped. Use range(lo, hi + 1) with an inclusive hi.
  • Updating the pair in the wrong order, for example prev1 = cur before prev2 = prev1. Then prev2 holds the new value and the recurrence reads the wrong house. Assign prev2 = prev1 first, then prev1 = cur.
  • Returning prev2 instead of prev1 at the end of the helper. After the final shift prev1 holds the answer for the row. Return prev1.
  • Slicing in Python with nums[:-1] and nums[1:] when n == 1. Both slices are empty, which hides the missing single-house case. The guard fixes it, and index bounds avoid copying the list.

Edge cases

  • [5]: one house, no neighbor. The answer is 5 and comes from the guard.
  • [2, 3]: two houses are neighbors in the circle in both directions. The answer is 3, the larger one.
  • [2, 3, 2]: all three houses are mutual neighbors. The answer is 3, not 4.
  • [1, 2, 3, 1]: robbing houses 1 and 3 gives 4. Rows [1,2,3] and [2,3,1] give 4 and 3.
  • [0, 0, 0]: all zeros. The answer is 0, and nothing in the code should go negative.
  • [1000] * 100: maximum size and value. Robbing 50 houses gives 50000, well inside int range.

Follow-ups interviewers ask

Why is it enough to solve only two rows, instead of tracking whether the first house was taken?
Any valid plan omits the first house or omits the last house, because it cannot hold both. Row 0..n-2 covers every plan without the last house, and row 1..n-1 covers every plan without the first. Together they cover every valid plan, so the larger row answer is the circular optimum. A flag-based recursion reaches the same answer with more bookkeeping.
Can you return the houses you robbed, not only the total?
Yes. Keep the full dp array from the second approach for the better row. Walk back from i = m. If dp[i] == dp[i-1], house i was skipped and you move to i-1; otherwise it was robbed and you move to i-2. Collect the robbed indices and reverse them. This needs the O(n) table, so the rolling-variable version cannot do it directly.
What changes if the houses form a tree, as in House Robber III?
The two-choice idea stays: rob a node or skip it. The state moves from an array index to a tree node. You run a depth-first search that returns two values for each subtree, the best with the root robbed and the best with it skipped. Robbing the root means both children must be skipped, and skipping the root lets each child take its own best. That is O(n) time with recursion depth equal to the tree height.

House Robber II FAQ

What is the time complexity of House Robber II?

It is O(n) time and O(1) extra space for the rolling-variable solution. You scan at most n-1 houses twice, doing constant work per house. A table-based version uses O(n) space with the same time.

Why use two linear passes for House Robber II?

The circle makes the first and last houses neighbors, so a valid plan skips at least one of them. Skipping the last leaves the row 0..n-2, and skipping the first leaves 1..n-1. Each row has no wrap-around, so the ordinary House Robber recurrence solves it exactly.

How is House Robber II different from House Robber (LeetCode 198)?

Only the adjacency of the first and last houses differs. House Robber has a straight row, so one DP pass is enough. House Robber II reuses that same pass on two overlapping rows and takes the maximum.

Can House Robber II be solved in O(1) extra space?

Yes. The recurrence reads only the previous two values, so two integers replace the table. Run it on 0..n-2 and again on 1..n-1, keeping only the two row results. You lose the ability to rebuild which houses were robbed, since that needs the full table.

Does House Robber II need memoized recursion, DFS or BFS?

No. A top-down recursion with a cache is a depth-first search over the choices and also works, in O(n) time with O(n) stack and cache space. BFS has no natural role here. The bottom-up array or rolling variables are shorter and avoid deep recursion.

What should House Robber II return for a single house?

It should return nums[0]. One house has no neighbor, so the circle rule does not apply. Without a special case, both row ranges are empty and the code returns 0.

Asked at

See which companies ask this — Pro

Practise it