House Robber II (LeetCode 213): Solution and Explanation

Medium
Array
Dynamic Programming

Houses sit in a circle, each holding some amount of money, and robbing two neighboring houses triggers an alarm. Because of the circle, the first and last houses are neighbors too. Return the most money you can take without robbing any two adjacent houses.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Start from the straight-line version. With houses in a row, a classic dynamic program works: the best total up to house i is either the best up to i - 1 (skip house i) or the best up to i - 2 plus house i (rob it). Only the last two values matter at each step, so two variables replace the whole table.

The circle adds exactly one new constraint: you cannot rob both the first and the last house. Trying to bolt that rule onto the DP directly is awkward, because the first decision affects the last one. A brute force over all valid subsets is exponential.

Instead, split into cases. Any valid plan either skips the first house or skips the last house, possibly both. If it skips the first house, the remaining houses form a straight line from index 1 to the end, and the circle no longer matters. If it skips the last house, the houses from index 0 to n - 2 form a straight line. So the answer is the better of the linear solution on nums[1:] and the linear solution on nums[:-1].

There is one edge case. With a single house, both slices would be empty and the answer would be 0, even though that house is its own neighbor in name only and can be robbed. The reference code returns nums[0] directly in that case.

Approach: Two linear DP passes

  1. If there is only one house, return nums[0].
  2. Define rob_linear(houses) with prev and curr both starting at 0, representing the best totals two houses back and one house back.
  3. For each amount n, update prev, curr = curr, max(curr, prev + n), choosing between skipping and robbing this house.
  4. Return curr, the best total for that straight line of houses.
  5. Run it on nums[:-1], which excludes the last house, and on nums[1:], which excludes the first.
  6. Return the larger of the two results.

Step-by-step example

nums = [2,7,9,3,1]
  1. A straight-line robber would take 2 + 9 + 1 = 12, but houses 0 and 4 are neighbors in the circle, so that plan is invalid.
  2. Case one is [2,7,9,3]. After 2 the state is (0, 2). After 7 it is (2, 7). After 9 it is (7, 11). After 3 it is (11, 11), since 7 + 3 = 10 is less than 11. The result is 11.
  3. Case two is [7,9,3,1]. After 7 the state is (0, 7). After 9 it is (7, 9). After 3 it is (9, 10). After 1 it is (10, 10). The result is 10.
  4. The larger of 11 and 10 is 11, which comes from robbing houses 0 and 2 (2 + 9).
  5. The answer is 11.

Code: Python, Java, C++

1class Solution:
2    def rob(self, nums: List[int]) -> int:
3        if len(nums) == 1:
4            return nums[0]
5
6        def rob_linear(houses):
7            prev, curr = 0, 0
8            for n in houses:
9                prev, curr = curr, max(curr, prev + n)
10            return curr
11
12        # Case 1: Rob houses 0 to n-2 (skip last)
13        # Case 2: Rob houses 1 to n-1 (skip first)
14        return max(rob_linear(nums[:-1]), rob_linear(nums[1:]))

Time and space complexity

Time

O(n)

Each of the two passes walks through about n houses doing constant work per house, and the slices are built in linear time.

Space

O(n)

The DP itself uses two variables, but nums[:-1] and nums[1:] create copies in Python. Passing start and end indices instead of slices brings it down to O(1).

Other approaches

Index-range passes without slicing (time O(n), space O(1))

Write the linear helper to take a start and end index and loop over that range of nums directly. The logic is identical, but no copies are made, so the extra space drops to a few variables.

Memoized recursion with a first-house flag (time O(n), space O(n))

Recurse over the index while carrying whether house 0 was robbed, and forbid robbing the last house when it was. It expresses the constraint directly but is more code and uses a memo table.

Common mistakes

  • Forgetting the single-house case. Both slices are empty, so the function would return 0 instead of the house's value.
  • Excluding both the first and the last house in one pass. That misses plans that rob one of them, for example taking only the last house when it is the largest.
  • Running the linear robber once on the whole array, which can rob both ends and break the circle rule.
  • Updating prev and curr in two separate statements without a temporary, so the new curr is computed from an already overwritten prev.

Frequently asked questions

Why does House Robber II run the algorithm twice?

The circle only forbids robbing both the first and last house. Every valid plan skips at least one of them, so solving the line without the first house and the line without the last house covers all cases.

What is the difference between House Robber and House Robber II?

In the first problem the houses form a straight line. In the second they form a circle, so the first and last houses are adjacent, which is handled by splitting into two straight-line subproblems.

What is the space complexity of House Robber II?

The DP only needs two variables. The Python version uses O(n) because slicing copies the list, but iterating over index ranges makes it O(1).