213. House Robber II
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem is a variation of the classic "House Robber" problem. The key difference is that the houses are arranged in a circle, meaning the first house and the last house are neighbors. This introduces a new constraint: if you rob the first house, you cannot rob the last one, and vice versa.
Solution
House Robber II in Python
class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
# Handle edge cases
if n == 0:
return 0
if n == 1:
return nums[0]
# Helper function to solve the original House Robber problem on a linear list.
# This is a space-optimized DP solution.
def rob_linear(sub_nums: List[int]) -> int:
rob1, rob2 = 0, 0
# [rob1, rob2, num, num+1, ...]
# For each house, we choose to either rob it or not.
# If we rob `num`, the max profit is `num + rob1` (profit from two houses ago).
# If we don't rob `num`, the max profit is `rob2` (profit from the previous house).
for num in sub_nums:
temp = max(num + rob1, rob2)
rob1 = rob2
rob2 = temp
return rob2
# The problem is broken down into two linear subproblems:
# 1. Rob houses from index 0 to n-2 (excluding the last house).
# 2. Rob houses from index 1 to n-1 (excluding the first house).
# The final answer is the maximum of these two scenarios.
# Case 1: Exclude the last house
# Slicing nums[:-1] creates a new list from index 0 to n-2.
max1 = rob_linear(nums[:-1])
# Case 2: Exclude the first house
# Slicing nums[1:] creates a new list from index 1 to n-1.
max2 = rob_linear(nums[1:])
return max(max1, max2)
House Robber II in Java
class Solution {
// Helper function to solve the original House Robber problem on a linear array (or subarray).
// This function takes start and end indices to avoid creating new arrays.
private int robLinear(int[] nums, int start, int end) {
int rob1 = 0; // Represents the max money that can be robbed up to house i-2
int rob2 = 0; // Represents the max money that can be robbed up to house i-1
// The state transition logic is as follows:
// For each house, we can either rob it or skip it.
// If we rob house i, total money = nums[i] + money from houses up to i-2 (rob1).
// If we skip house i, total money = money from houses up to i-1 (rob2).
// We take the maximum of these two choices.
// [..., rob1, rob2, nums[i], nums[i+1], ...]
for (int i = start; i <= end; i++) {
int temp = Math.max(nums[i] + rob1, rob2);
rob1 = rob2;
rob2 = temp;
}
return rob2;
}
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
// Handle the edge case of a single house.
if (n == 1) {
return nums[0];
}
// The problem is broken down into two linear subproblems:
// 1. Rob houses from index 0 to n-2 (excluding the last house).
// 2. Rob houses from index 1 to n-1 (excluding the first house).
// The final answer is the maximum of these two scenarios.
// Case 1: Rob houses from 0 to n-2.
int max1 = robLinear(nums, 0, n - 2);
// Case 2: Rob houses from 1 to n-1.
int max2 = robLinear(nums, 1, n - 1);
return Math.max(max1, max2);
}
}
House Robber II in C++
class Solution {
private:
// Helper function to solve the original House Robber problem on a linear array (or subarray).
// This function takes start and end indices to avoid creating new vectors.
int robLinear(const std::vector<int>& nums, int start, int end) {
int rob1 = 0; // Represents the max money that can be robbed up to house i-2
int rob2 = 0; // Represents the max money that can be robbed up to house i-1
// The state transition logic is as follows:
// For each house, we can either rob it or skip it.
// If we rob house i, total money = nums[i] + money from houses up to i-2 (rob1).
// If we skip house i, total money = money from houses up to i-1 (rob2).
// We take the maximum of these two choices.
// [..., rob1, rob2, nums[i], nums[i+1], ...]
for (int i = start; i <= end; ++i) {
int temp = std::max(nums[i] + rob1, rob2);
rob1 = rob2;
rob2 = temp;
}
return rob2;
}
public:
int rob(std::vector<int>& nums) {
int n = nums.size();
// According to constraints, 1 <= nums.length <= 100, so n=0 is not possible.
// Handle the edge case of a single house.
if (n == 1) {
return nums[0];
}
// The problem is broken down into two linear subproblems:
// 1. Rob houses from index 0 to n-2 (excluding the last house).
// 2. Rob houses from index 1 to n-1 (excluding the first house).
// The final answer is the maximum of these two scenarios.
// Case 1: Rob houses from 0 to n-2.
int max1 = robLinear(nums, 0, n - 2);
// Case 2: Rob houses from 1 to n-1.
int max2 = robLinear(nums, 1, n - 1);
return std::max(max1, max2);
}
};
House Robber II in TypeScript
function rob(nums: number[]): number {
const n = nums.length;
// Handle edge cases
if (n === 0) {
return 0;
}
if (n === 1) {
return nums[0];
}
// Helper function to solve the original House Robber problem on a linear array.
// This is a space-optimized DP solution.
const robLinear = (subNums: number[]): number => {
let rob1 = 0; // Represents the max money that can be robbed up to house i-2
let rob2 = 0; // Represents the max money that can be robbed up to house i-1
// [rob1, rob2, num, num+1, ...]
// For each house, we choose to either rob it or not.
// If we rob `num`, the max profit is `num + rob1` (profit from two houses ago).
// If we don't rob `num`, the max profit is `rob2` (profit from the previous house).
for (const num of subNums) {
const temp = Math.max(num + rob1, rob2);
rob1 = rob2;
rob2 = temp;
}
return rob2;
};
// The problem is broken down into two linear subproblems:
// 1. Rob houses from index 0 to n-2 (excluding the last house).
// 2. Rob houses from index 1 to n-1 (excluding the first house).
// The final answer is the maximum of these two scenarios.
// Case 1: Exclude the last house. `slice(0, n-1)` extracts elements from index 0 to n-2.
const max1 = robLinear(nums.slice(0, n - 1));
// Case 2: Exclude the first house. `slice(1)` extracts elements from index 1 to the end.
const max2 = robLinear(nums.slice(1));
return Math.max(max1, max2);
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.