Python 0213.py
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
# idea: skip one or two houses: never more, never less
@cache
def deeper(pos, stop):
if pos >= stop:
return 0
return nums[pos] + max(deeper(pos+2, stop), deeper(pos+3, stop))
a = deeper(2, len(nums))
b = deeper(1, len(nums))
c = deeper(0, len(nums) - 1)
return max(a, b, c)
Difficulty
and has an acceptance rate of about 45% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “House Robber” problem for a circular arrangement of houses. The rob method receives a list of non-negative integers, each representing the amount of money in a house, and returns the maximum amount that can be stolen without triggering an alarm. The algorithm treats the circular constraint by evaluating three distinct robbery scenarios and selecting the best outcome.
Key Steps
Handling a Single-House Input
if len(nums) == 1:
return nums[0]
When the input list contains exactly one element, the only possible robbery amount is the value of that house. The early return prevents unnecessary recursion and respects the circular rule, where the single house is both the first and the last.
Defining the Recursive Helper
@cache
def deeper(pos, stop):
if pos >= stop:
return 0
return nums[pos] + max(deeper(pos+2, stop), deeper(pos+3, stop))
A memoized inner function deeper computes the optimal loot starting from a given position pos up to, but not including, the index stop. The base case returns zero when the current position reaches or exceeds the stop boundary. The recursive step adds the current house’s value to the larger of the two possibilities: skipping one house (pos+2) or skipping two houses (pos+3). This reflects the rule that after robbing a house, the next immediate house cannot be robbed, but the algorithm also explores the option of skipping an additional house to capture scenarios where a later house yields a higher total.
Evaluating the Three Scenarios
a = deeper(2, len(nums))
b = deeper(1, len(nums))
c = deeper(0, len(nums) - 1)
return max(a, b, c)
Three calls to deeper represent the distinct ways to break the circular dependency:
- Starting at index 2 and allowing robbery up to the end of the list (
a). This implicitly skips the first two houses, ensuring that the first house is not considered while still allowing the last house. - Starting at index 1 and proceeding to the end (
b). This skips only the first house, permitting the last house to be part of the solution. - Starting at index 0 but stopping before the last house (
c). This includes the first house while explicitly excluding the last house.
The final result is the maximum of these three computed totals, guaranteeing compliance with the circular restriction.
Edge Cases Handled
The early return for a single-element list addresses the edge case where the circular nature collapses to a single house. The base condition inside deeper (pos >= stop) safely terminates recursion when the starting index exceeds the allowed range, covering scenarios where the recursion steps beyond the list length due to the +2 or +3 jumps. By using stop as an exclusive bound, the function correctly avoids accessing out-of-range indices, even when the list length is small (for example, length 2 or 3).
Performance Optimizations
Memoization is applied through the @cache decorator on the deeper function. This caches the result of each (pos, stop) pair, preventing exponential recomputation of overlapping subproblems. As the recursion explores only forward jumps of two or three positions, the number of distinct states is bounded by the length of the input list, and each state is evaluated at most once. Consequently, the algorithm runs efficiently even for larger inputs, leveraging the cached results to achieve a linear number of evaluations rather than a combinatorial explosion.
ELI5 - Simplified Explanation
Imagine a long street filled with houses, and each house has a gift of treats inside. The goal is to collect as many treats as possible, but there is a tricky rule. If a house is picked, the very next house must be skipped because it has a loud alarm. This means deciding which houses to visit while jumping over the ones that are not safe.
The code looks at the street by trying out different starting points. It thinks about taking a house and then jumping ahead either one or two more houses to find the next treat. This process happens over and over, jumping across the street and keeping track of the biggest pile of treats gathered. Because there are so many houses, the code remembers the totals it has already calculated so it does not have to do the same work twice. After checking all the different paths, it chooses the path that leads to the largest pile of treats.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| bujosa | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| martianoff | Scala | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| bujosa | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| martianoff | Scala | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 198: House Robber
- problem 256: Paint House
- problem 276: Paint Fence
- problem 337: House Robber III
- problem 600: Non-negative Integers without Consecutive Ones
- problem 656: Coin Path
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality