House Robber IV solution explained
To solve House Robber IV, binary search on the answer: for a candidate limit, scan the houses left to right and greedily take every house whose amount is at most the limit, skipping the house right after each one you take. If the scan takes at least k houses, the limit works, so search lower; otherwise search higher. Each check is O(n), so the whole solution is O(n log M), where M is the range of amounts, or O(n log n) over the sorted distinct amounts.
By Evin JohnPublished 8 min read
The problem in plain words
A street has houses in a row, and house i holds amounts[i], a positive integer. A thief will take from at least k houses and refuses to take from two houses that stand next to each other. Among the houses chosen, the thief's "capability" is the single largest amount taken. Return the smallest capability that still lets the thief choose k or more houses. You may assume such a choice exists, which means k is at most about half the number of houses, rounded up.
amounts = [7, 3, 9, 4, 2, 8]
k = 2: take houses 1 and 4 (amounts 3 and 2) -> answer 3
k = 3: take houses 0, 3, 5 (amounts 7, 4, 8) -> answer 8
(no three non-adjacent houses all hold 7 or less)Note that "at least k" behaves like "exactly k": dropping extra houses from a choice can only lower or keep its largest amount. Also note that the answer is always one of the amounts in the array, since the largest amount taken is the amount of some house.
Why interviewers pick it
The name suggests dynamic programming, because earlier problems in the series are DP over "take this house or skip it". This one rewards stepping back. The objective is a minimum of a maximum, and that phrasing is the strongest hint in the problem: when you can cheaply answer "is limit L good enough?" and the answer only flips once as L grows, binary search over L does the rest. Interviewers want to see you recognize that shape and justify the greedy check rather than just assert it. Variations they reach for:
- Prove the greedy check. Why is taking the first allowed house always safe?
- Replace the greedy with DP. Count the most houses you can take under the limit with a take-or-skip recurrence. Same answer, more code.
- Houses on a circle. The first and last are adjacent. Run the check twice, once without the first house and once without the last, the trick from the circular robber problem.
- Search space. Binary search over the integer range or over the sorted distinct amounts, and explain why both return a real amount.
- Other min-max problems. Splitting an array into k parts with the smallest largest sum, or shipping packages within d days, use the same frame.
Brute force: try every valid choice
The most literal approach lists every set of exactly k houses, discards sets with two neighbors, and records the smallest largest amount among the rest. The number of sets is a binomial coefficient, which explodes quickly, so this is only usable for very small arrays. It is still worth saying first, because it pins down the definition, and it is the reference our tests compared against.
from itertools import combinations
def min_capability_brute(amounts, k):
best = None
for picks in combinations(range(len(amounts)), k):
if all(b - a > 1 for a, b in zip(picks, picks[1:])):
worst = max(amounts[i] for i in picks)
if best is None or worst < best:
best = worst
return bestA middle step is to sort the distinct amounts and test them one by one from the smallest, using the linear check described next, until one works. That is O(n) per check and up to n checks, so O(n²). Binary search replaces the linear scan of candidates with a halving one.
The check: can we take k houses with nothing above L?
Fix a limit L. Houses with amounts above L are off limits; the rest are allowed. Walk left to right. When you reach an allowed house, take it and jump two places, since its right neighbor can no longer be taken. When you reach a forbidden house, move one place. Count what you took.
Why is taking the earliest allowed house never a mistake? Suppose some best selection under L starts at house j and the first allowed house is i, with i at most j. Swap j for i. The next house in that selection is at j + 2 or later, so it is still at least two away from i, and the selection keeps its size. Repeating the argument from each taken house shows the greedy count is as large as any possible count.
def can_take(amounts, limit, k):
taken = 0
i = 0
while i < len(amounts):
if amounts[i] <= limit:
taken += 1
if taken >= k:
return True
i += 2
else:
i += 1
return False
def min_capability(amounts, k):
lo, hi = min(amounts), max(amounts)
while lo < hi:
mid = (lo + hi) // 2
if can_take(amounts, mid, k):
hi = mid
else:
lo = mid + 1
return loThe range search returns the smallest integer limit that works. Feasibility can only change at a value that appears in the array, so that smallest working integer is an actual amount. The JavaScript version searches the sorted distinct amounts instead, which makes that fact obvious and costs O(n log n) for the sort. Note the loop index trick: incrementing i inside the loop body plus the loop's own increment skips the neighbor.
function minCapability(amounts, k) {
const values = [...new Set(amounts)].sort((a, b) => a - b);
const canTake = (limit) => {
let taken = 0;
for (let i = 0; i < amounts.length; i++) {
if (amounts[i] <= limit) {
taken++;
if (taken >= k) return true;
i++;
}
}
return false;
};
let lo = 0;
let hi = values.length - 1;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (canTake(values[mid])) hi = mid;
else lo = mid + 1;
}
return values[lo];
}Trace k = 3 on the example. Limit 8: take 7, skip 3, 9 is too big, take 4, skip 2, take 8. Three houses, so 8 works. Limit 7: take 7, skip 3, 9 is too big, take 4, skip 2, 8 is too big. Two houses, so 7 fails, and the answer is 8.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Every k-subset of houses | O(C(n, k) · k) | O(k) |
| Test sorted distinct amounts one by one | O(n²) | O(n) for the sorted values |
| Binary search over the value range | O(n log M) | O(1) |
| Binary search over sorted distinct amounts | O(n log n) | O(n) |
| Binary search with a DP check instead of greedy | O(n log M) | O(1) with two rolling variables |
Edge cases
- k = 1: the answer is the smallest amount.
- One house: the answer is its amount.
- k equal to the maximum possible, such as 3 out of 5 houses: only houses 0, 2 and 4 fit, so the answer is their largest amount.
- All amounts equal: that amount.
- Small amounts placed next to each other, like [1, 1, 9, 9]: only one of the 1s can be taken, which forces the answer up.
- Very large amounts: (lo + hi) // 2 is safe in Python; in fixed-width languages use lo + (hi - lo) / 2.
Common mistakes
- Treating it as a sum problem and maximizing the total, as in the earlier robber problems.
- Taking the k smallest amounts without checking adjacency.
- Forgetting to skip the next house after taking one, so neighbors get counted together.
- Writing the binary search with hi = mid - 1 after a success, which can step past the answer.
- Claiming the greedy works without the exchange argument when the interviewer asks why.
How to explain it out loud
Fictional example
- Candidate
- We are minimizing the largest amount taken, and if a limit allows k houses then any higher limit does too. That monotonic yes-no answer means I can binary search on the limit.
- Candidate
- To test a limit, I scan once and take every allowed house as early as possible, skipping its neighbor.
- Interviewer
- Why is taking the earliest one safe?
- Candidate
- If a better selection starts later, I can swap its first house for the earlier one without creating a neighbor conflict, so greedy never ends up with fewer houses.
- Candidate
- That is O(n) per check and about log of the value range checks.
Related walkthroughs
For a change from arrays, Number of Closed Islands is a grid search with a twist on which regions count, and Longest ZigZag Path in a Binary Tree is another problem where a small rule about what may follow what drives the whole solution. Meeting Rooms II is a good next stop for greedy reasoning over sorted values.
How Natively fits into practice
Natively, on Mac or Windows, can read this problem from a screenshot while you practice and answer with an approach and code in its overlay. That is a quick way to confirm a binary search boundary you are unsure of, or to ask only for the exchange argument. When you rehearse the explanation aloud, its transcript shows whether you named the min-max pattern before diving into code. See the AI interview assistant for more.
Questions people ask
How do you solve House Robber IV?
Binary search on the limit for the largest single amount. For each limit, scan left to right and take every allowed house as early as possible, skipping its neighbor; if you reach k houses the limit works.
Why does binary search work for House Robber IV?
Feasibility is monotonic. If some limit lets you take k non-adjacent houses, any larger limit allows the same houses, so the answers form a no-then-yes pattern.
Why is the greedy check correct in House Robber IV?
Taking the earliest allowed house never hurts: any valid selection that starts later can swap its first house for the earlier one without creating adjacent picks.
What is the time complexity of House Robber IV?
O(n log M) when searching the value range, where M is the spread of amounts, or O(n log n) when searching the sorted distinct amounts.
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.
