House Robber II solution explained
House Robber II is the circular version of House Robber: the values sit in a ring, so the first and last positions count as neighbors. Because those two can never both be taken, solve the straight-line problem twice, once without the last value and once without the first, and return the larger result. That keeps the solution at O(n) time and O(1) extra space, with one special case for a ring of a single value.
By Evin JohnPublished 7 min read
The task, restated
A food truck owner can park at stops along a circular bus loop. Each stop has a known daily take, but parking at one stop means the two stops on either side of it lose their permits for that day. The loop closes on itself, so the final stop sits beside stop zero. Given the list of takes in loop order, return the highest total the owner can reach. In plain terms: an array of non-negative integers arranged in a circle, choose indexes with no two adjacent around the circle, and maximize their sum.
| Ring | Best total | Why |
|---|---|---|
| [7, 1, 1, 7] | 8 | The two 7s touch across the seam, so take one 7 and the 1 that is not beside it |
| [5, 2, 6, 4] | 11 | 5 + 6; the first and third are not neighbors |
| [2, 8, 3, 8] | 16 | Both 8s, at indexes 1 and 3, which are not neighbors |
| [4, 9] | 9 | In a ring of two, the two values are neighbors |
| [3] | 3 | One value has no neighbor but itself |
The first row is the one to show the interviewer. On a straight line, [7, 1, 1, 7] allows 7 + 7 = 14. On a ring, the seam between the last and first value removes that option and the answer drops to 8. If your code returns 14 here, it is still solving the first problem.
What the interviewer is checking
This problem usually arrives right after the straight-line version, sometimes in the same session. The interviewer wants to see you reuse a working function instead of inventing a new recurrence with a pile of flags. The key sentence is a case split you can justify: in any legal pick, at least one of the two seam values is left out. Candidates who state that sentence first, then code, tend to finish quickly. Candidates who start adding a taken-first boolean to the state can also get there, but they spend longer and leave more room for off-by-one bugs.
Brute force: check every subset against the ring
With n values there are 2^n subsets. For each one, check that no two chosen indexes are next to each other, treating n - 1 and 0 as next to each other, and track the best sum. A bitmask makes the check short. This is far too slow beyond about twenty values, but it is a reliable reference to test the fast version against, and that is how the code on this page was checked.
def ring_best_slow(takes):
n = len(takes)
best = 0
for mask in range(1 << n):
ok = True
for i in range(n):
j = (i + 1) % n
if n > 1 and i != j and (mask >> i) & 1 and (mask >> j) & 1:
ok = False
break
if ok:
best = max(best, sum(takes[i] for i in range(n) if (mask >> i) & 1))
return bestThe split that makes it easy
Take any legal pick on the ring. The first and last values are neighbors, so the pick cannot contain both. That leaves two families. Family A never uses the last value, which means it is a legal pick on the straight line from index 0 to n - 2. Family B never uses the first value, which means it is a legal pick on the straight line from index 1 to n - 1. Every legal ring pick falls into at least one family, and every legal pick in either family is legal on the ring, because removing one seam value breaks the circle into a line. So the ring answer is the larger of the two line answers.
| Run | Values used | Line answer |
|---|---|---|
| Without the last value | [7, 1, 1] | 8 (7 + 1) |
| Without the first value | [1, 1, 7] | 8 (1 + 7) |
| Ring answer | max of the two | 8 |
There is one trap. When the ring has a single value, both runs are empty and return 0, which is wrong: one value has no other neighbor and can be taken. Handle that case before the split.
Optimal code: one helper, two index ranges
Pass index bounds into the helper instead of slicing the list. Slicing would copy up to n values twice; bounds keep extra space at O(1).
def line_best(takes, lo, hi):
"""Best non-adjacent sum using takes[lo..hi] inclusive."""
prev, cur = 0, 0
for i in range(lo, hi + 1):
prev, cur = cur, max(cur, prev + takes[i])
return cur
def ring_best(takes):
n = len(takes)
if n == 0:
return 0
if n == 1:
return takes[0]
return max(line_best(takes, 0, n - 2), line_best(takes, 1, n - 1))function lineBest(takes, lo, hi) {
let prev = 0;
let cur = 0;
for (let i = lo; i <= hi; i++) {
const nextCur = Math.max(cur, prev + takes[i]);
prev = cur;
cur = nextCur;
}
return cur;
}
function ringBest(takes) {
const n = takes.length;
if (n === 0) return 0;
if (n === 1) return takes[0];
return Math.max(lineBest(takes, 0, n - 2), lineBest(takes, 1, n - 1));
}A ring of two needs no special branch: each run covers one value, so the answer is the larger value, which is right because the two values are neighbors.
Another way: carry a flag for the first value
Some people prefer a single pass with two sets of rolling totals, one where the first value is allowed and the last is forbidden, one where the first is forbidden. That is the same split written in one loop. It works, but it is harder to read and easier to get wrong at the boundaries. If an interviewer asks for one pass, mention it; otherwise the two-call version is cleaner and has the same complexity.
Time and space
| Version | Time | Extra space |
|---|---|---|
| Every subset | O(2^n · n) | O(1) besides the loop |
| Two line runs with tables | O(n) | O(n) |
| Two line runs with rolling totals and index bounds | O(n) | O(1) |
| Two runs on sliced copies | O(n) | O(n) for the copies |
Edge cases
- Empty ring: 0.
- Ring of one: the value itself. This is the case most solutions miss.
- Ring of two: the larger value.
- Ring of three: any single value, so the maximum, because every pair of positions in a triangle touches.
- All values equal: floor(n / 2) times the value for n of at least 2, since a ring with an odd count loses one slot to the seam.
Mistakes to avoid
- Running the straight-line solution once on the full ring, which returns 14 for [7, 1, 1, 7].
- Dropping both seam values in one run, which loses picks such as [2, 8, 3, 8] where the last value belongs in the answer.
- Returning 0 for a ring of one because both ranges are empty.
- Off-by-one bounds: the first run ends at n - 2, the second starts at 1, both inclusive in the code above.
- Rewriting the recurrence from scratch rather than reusing the line helper you already trust.
How to explain it out loud
Fictional example
- Candidate
- The only thing the circle adds is that the first and last values are now neighbors, so no answer can use both.
- Candidate
- That means every answer either skips the last value or skips the first one. I will run my line function on indexes 0 through n minus 2, then on 1 through n minus 1, and return the larger.
- Candidate
- One value is a special case because both ranges are empty. Total cost is two linear passes, so O(n) time and constant space.
Related problems
Start with House Robber if the line recurrence is new to you; this page assumes it. Decode Ways keeps the same two rolling values but counts paths instead of maximizing. Maximum Product Subarray is another problem where the trick is to carry two running values at once, there a largest and a smallest product.
Where Natively fits
If you practice a set of related problems in one sitting, Natively can take a screenshot of the circular version, explain the case split, and offer code in Python or JavaScript for you to check against your own. It runs on Mac and Windows and keeps a transcript of your mock session, which makes it easy to see whether you mentioned the single-value case before the interviewer had to ask. Read more on the AI interview assistant page.
Questions people ask
How do you solve House Robber II?
Since the first and last values are neighbors, no answer uses both. Run the straight-line House Robber solution on everything except the last value, then on everything except the first, and return the larger result.
What is the time complexity of House Robber II?
O(n) time, because it makes two linear passes. With rolling variables and index bounds instead of sliced copies, extra space is O(1).
What edge case breaks most House Robber II solutions?
A ring with a single value. Both straight-line ranges are empty and return 0, but the correct answer is the value itself, so handle n = 1 before splitting.
How is House Robber II different from House Robber?
The values form a circle, so the last position is adjacent to the first. On a line, [7, 1, 1, 7] allows 14; on a ring the two 7s touch and the best total is 8.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
