House Robber II (LeetCode 213): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- If there is only one house, return
nums[0]. - Define
rob_linear(houses)withprevandcurrboth starting at 0, representing the best totals two houses back and one house back. - For each amount
n, updateprev, curr = curr, max(curr, prev + n), choosing between skipping and robbing this house. - Return
curr, the best total for that straight line of houses. - Run it on
nums[:-1], which excludes the last house, and onnums[1:], which excludes the first. - Return the larger of the two results.
Step-by-step example
nums = [2,7,9,3,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.
- 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.
- 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.
- The larger of 11 and 10 is 11, which comes from robbing houses 0 and 2 (2 + 9).
- 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:]))1class Solution {
2 public int rob(int[] nums) {
3 if (nums.length == 1) return nums[0];
4
5 // Case 1: Skip last, Case 2: Skip first
6 return Math.max(
7 robLinear(nums, 0, nums.length - 2),
8 robLinear(nums, 1, nums.length - 1)
9 );
10 }
11
12 private int robLinear(int[] nums, int start, int end) {
13 int prev = 0, curr = 0;
14 for (int i = start; i <= end; i++) {
15 int temp = curr;
16 curr = Math.max(curr, prev + nums[i]);
17 prev = temp;
18 }
19 return curr;
20 }
21}1class Solution {
2public:
3 int rob(vector<int>& nums) {
4 if (nums.size() == 1) return nums[0];
5
6 return max(
7 robLinear(nums, 0, nums.size() - 2),
8 robLinear(nums, 1, nums.size() - 1)
9 );
10 }
11
12private:
13 int robLinear(vector<int>& nums, int start, int end) {
14 int prev = 0, curr = 0;
15 for (int i = start; i <= end; i++) {
16 int temp = curr;
17 curr = max(curr, prev + nums[i]);
18 prev = temp;
19 }
20 return curr;
21 }
22};Time and space complexity
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.
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
prevandcurrin two separate statements without a temporary, so the newcurris computed from an already overwrittenprev.
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).