House Robber II – Solution & Complexity
Solution Walkthrough
Step 1: Why the circle matters
- In the linear House Robber you may take any non-adjacent subset.
- Here house
0and housen-1are neighbors too, so you can never rob both of them. - A single house is a special case: just return it.
Step 2: Split into two linear problems
- Either you skip the last house or you skip the first house (you cannot keep both).
- So the answer is the better of robbing houses
0..n-2and robbing houses1..n-1, each solved as an ordinary linear House Robber. - Here is a first version that fills an explicit DP array for each range.
Step 3: Collapse the linear pass to O(1) space
- The linear recurrence
best[i] = max(best[i-1], best[i-2] + arr[i])only needs the previous two results. - Replace the DP array with two rolling variables and reuse that helper on both ranges.
- The linear recurrence
Step 4: Optimal two-pass solution
robRangescans a slice keepingprevOneandprevTwo.- Call it on
nums[:-1]andnums[1:], then take the maximum. Handle the length-1 street before slicing so neither range becomes empty in a way that drops the only house.
Step 5: Dry run
Trace
nums = [1,2,3,1].- Range
[1,2,3](drop the last house): best loot is4by robbing1and3. - Range
[2,3,1](drop the first house): best loot is3(either3alone or2 + 1). - Answer is
max(4, 3) = 4.
- Range
Step 6: Common mistakes and follow-ups
- Forgetting the length-1 case and slicing into two empty ranges, which returns
0instead of the single house. - Trying to write one circular recurrence with a flag; the two-pass reduction is simpler and less error-prone.
- Double-counting by allowing both house
0and housen-1. - Follow-up: how would you also return which houses were robbed, not just the total?
- Forgetting the length-1 case and slicing into two empty ranges, which returns
Step 7: Edge cases to test mentally
- One house: return it directly.
- Two houses: they are adjacent on both sides, so take the larger.
- The wrap neighbor can make a locally greedy pick wrong, so always compare both ranges.
Step 8: Final full solution and complexity
Reduce the circle to two linear passes and keep only rolling state in each. Time is
O(n)and extra space isO(1).