House Robber II
LeetCode 213 · Medium · solution, intuition & step-by-step walkthrough
Circle → max(rob_line(nums[1:]), rob_line(nums[:-1])).
This is how I solved House Robber II (LeetCode 213), a medium problem from the 1D / Fibonacci pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
The houses form a circle, so the first and last are neighbours and can never both be robbed. Break the circle by solving the straight-line House Robber twice: once without the first house and once without the last, and keep the better result.
Approach
- 1
Reuse the linear House Robber DP as rob_all(nums).
- 2
Case A: drop the first house — the last house is now free to take.
- 3
Case B: drop the last house — the first house is now free to take.
- 4
Return the larger of the two; a single house is returned directly.
How I solved it
Two linear passesPythonO(n) time · O(n) space
class Solution:
def rob_all(self, nums: List[int]) -> int:
#eithter i can rob and go to index-2
#or skip and go to index-1
if len(nums)==1:
return nums[0]
n = len(nums)
dp=[float("-inf")]*n
dp[0]=nums[0]
dp[1]=max(nums[0],nums[1])
for index in range(2,n):
rob = nums[index]+dp[index-2]
dontrob = dp[index-1]
dp[index]=max(rob,dontrob)
return dp[n-1]
def rob(self, nums: List[int]) -> int:
if len(nums)==1:
return nums[0]
#skip first or skip last since they are adjacent and get max for these two options
return max(self.rob_all(nums[1:]),self.rob_all(nums[:len(nums)-1]))
House Robber II — FAQ
What is the intuition behind House Robber II?
The houses form a circle, so the first and last are neighbours and can never both be robbed. Break the circle by solving the straight-line House Robber twice: once without the first house and once without the last, and keep the better result.
How do you solve House Robber II (LeetCode 213)?
1. Reuse the linear House Robber DP as rob_all(nums). 2. Case A: drop the first house — the last house is now free to take. 3. Case B: drop the last house — the first house is now free to take. 4. Return the larger of the two; a single house is returned directly.
What is the time and space complexity of House Robber II?
Time: O(n). Space: O(n). (Accepted approach: Two linear passes.)
What are common mistakes in House Robber II?
With one house, slicing both ends would leave nothing — handle len == 1 first. Don't try to track 'was the first house robbed' inside one pass; two passes is simpler and safe.