Problem 213

Abstract / Summary

A thief wants to steal from houses arranged in a circle without robbing adjacent houses find the maximum amount he can steal

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
17 lines | 503 bytes | submitted September 4, 2023 | GitHub   7% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.46 | σ = 1.74

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
51 links | 36 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'House Robber 2 (LeetCode 213) | Full solution with easy explanation | Diagrams | Study Algorithms'
Nikhil Lohia 11 mins
House Robber 2 (LeetCode 213) | Full solution with easy explanation | Diagrams | Study Algorithms
YouTube video 'house robber ii | house robber II | house robber ii leetcode | leetcode 213 | DP'
Naresh Gupta 10 mins
house robber ii | house robber II | house robber ii leetcode | leetcode 213 | DP
YouTube video 'House Robber II | Live Coding with Explanation | Leetcode - 213'
Algorithms Made Easy 7 mins
House Robber II | Live Coding with Explanation | Leetcode - 213
YouTube video 'HOUSE ROBBER II | LEETCODE 213 | PYTHON SOLUTION'
Cracking FAANG 9 mins
HOUSE ROBBER II | LEETCODE 213 | PYTHON SOLUTION
YouTube video 'House Robber II | Leet code 213 | Theory explained + Python code'
Sai Anish Malla 12 mins
House Robber II | Leet code 213 | Theory explained + Python code
YouTube video 'Daily Leetcode #197: Oct 14, 2020 - 213. House Robber II'
Programming Live with Larry 16 mins
Daily Leetcode #197: Oct 14, 2020 - 213. House Robber II
YouTube video 'LeetCode 213. House Robber II'
Happy Coding 15 mins
LeetCode 213. House Robber II
YouTube video 'Leetcode 213: House Robber II in Telugu | Dynamic Programming | Python DSA | srkcodes'
Srk Codes 19 mins
Leetcode 213: House Robber II in Telugu | Dynamic Programming | Python DSA | srkcodes
YouTube video '47. Leetcode 213. House Robber II : JAVA'
Web Fusion with Bharadwaj 21 mins
47. Leetcode 213. House Robber II : JAVA
YouTube video '102. Leetcode 213. House Robber II : Javascript'
Web Fusion with Bharadwaj 22 mins
102. Leetcode 213. House Robber II : Javascript
YouTube video 'House Robber II - LeetCode 213 - Python'
Alpha-Code 37 mins
House Robber II - LeetCode 213 - Python
YouTube video 'Day 312: LeetCode Problem 213. House Robber II - Swift'
iOSxBank 13 mins
Day 312: LeetCode Problem 213. House Robber II - Swift
YouTube video 'Leetcode 213 | House Robber II 🔥 Circular DP + Recursion + Memo | Beat Interview DP'
Study Placement 18 mins
Leetcode 213 | House Robber II 🔥 Circular DP + Recursion + Memo | Beat Interview DP
YouTube video 'LeetCode 213 | House Robber II | Included, Excluded | Java'
Sleepy Cracker 4 mins
LeetCode 213 | House Robber II | Included, Excluded | Java
YouTube video 'House Robber II - Leetcode 213 | Using Dynamic Programming solution from House Robber 1'
Code With K5KC 10 mins
House Robber II - Leetcode 213 | Using Dynamic Programming solution from House Robber 1
YouTube video '188. Leetcode 213. House Robber II : JAVA'
Web Fusion with Bharadwaj 17 mins
188. Leetcode 213. House Robber II : JAVA
YouTube video 'House Robber II - LeetCode #213 - C++'
Sean Chuah 6 mins
House Robber II - LeetCode #213 - C++
YouTube video 'Leetcode 213. House Robber II [ JAVASCRIPT ].'
Web Fusion with Bharadwaj 17 mins
Leetcode 213. House Robber II [ JAVASCRIPT ].
YouTube video 'Leetcode 213 | House Robber II | Dynamic Programming | Medium'
Code with Akhil 7 mins
Leetcode 213 | House Robber II | Dynamic Programming | Medium
YouTube video 'No Sound Leetcode 213: House Robber II'
ExtremeProgrammer 4 mins
No Sound Leetcode 213: House Robber II
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

6 similar problems

Solved On The Same Day

25 solutions   September 4, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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