Taro Logo

House Robber

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+31
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.7K views
Topics:
ArraysDynamic Programming

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected range of the length of the `nums` array, and how small can the input be (e.g., could it be empty or have only one house)?
  2. Can the values inside the `nums` array contain negative numbers, or are all amounts strictly non-negative integers?
  3. Should we consider the first and the last house in the array as adjacent, or is this strictly a linear street of houses?
  4. What is the expected return type and value if the input array is empty or if no houses can be robbed?
  5. Are we only required to return the maximum amount of money, or do we also need to return the specific indices or houses that were robbed?

Brute Force Solution

Approach

Imagine you are trying to find the absolute most money you can steal from a row of houses without setting off the security alarms by robbing two neighbors in a row. The brute force approach is to meticulously map out and test every single combination of houses you could possibly rob, ensuring you never pick two next-door neighbors.

Here's how the algorithm would work step-by-step:

  1. Start at the very beginning of the street and look at the first house.
  2. Decide on your first path by imagining you rob this first house, which means you must skip the next one and then consider all possible valid combinations for the houses further down the street.
  3. Decide on your second path by imagining you skip this first house entirely, which means you are now free to consider robbing the second house and exploring all possible combinations from there.
  4. Continue this process of making a choice at every house to either rob it (and skip the next) or skip it, branching out into every conceivable sequence of decisions until you reach the end of the street.
  5. Calculate the total amount of money you would collect for every single one of those completed paths.
  6. Compare the totals from all the paths you explored.
  7. Select the largest total amount you found, as that represents the most money you can steal without triggering the alarms.

Code Implementation

def rob(houses):
    def calculate_maximum_loot(current_house_index):
        if current_house_index >= len(houses):
            return 0

        # Branch into two choices: either rob the current house or skip it entirely to explore all paths
        loot_from_robbing_current = houses[current_house_index] + calculate_maximum_loot(current_house_index + 2)

        loot_from_skipping_current = calculate_maximum_loot(current_house_index + 1)

        # Compare both branches to find the maximum possible loot without triggering neighborhood alarms
        return max(loot_from_robbing_current, loot_from_skipping_current)

    return calculate_maximum_loot(0)

Big(O) Analysis

Time Complexity
O(2ⁿ) – The plain English approach relies on a brute force decision tree where at every single one of the n houses, you branch out into two distinct choices: either rob the house and skip the next, or skip the house entirely. Because you make a binary choice of two paths for each of the n houses, the recursion generates a complete binary decision tree of depth n. This results in approximately 2 to the power of n total paths and completed calculations, which simplifies to an exponential time complexity of O(2ⁿ).
Space Complexity
O(2^N) – The brute force recursive exploration described in the steps builds a massive decision tree by branching twice at every single house. This recursive process consumes memory on the call stack proportional to the height of the tree, which can reach a maximum depth of N corresponding to the total number of houses on the street. Because every house presents a choice to rob or skip, the number of simultaneous active paths and total stack frames required grows exponentially with the input size N. Therefore, the maximum auxiliary space complexity simplifies to O(2^N) due to the sheer volume of recursive branches evaluated.

Optimal Solution

Approach

Imagine you are walking down a street of houses, deciding which ones to target while keeping in mind that you cannot trigger alarms by hitting two adjacent properties. Instead of testing every single combination of houses, the smart strategy is to figure out the best possible total you can gather up to each house by looking only at the results of the houses immediately behind you.

Here's how the algorithm would work step-by-step:

  1. Look at the very first house on the street and note the value of the goods inside, since your best option so far is just to take that amount.
  2. Move to the second house and compare its value with the first house, deciding to take whichever value is higher because you cannot take from both without getting caught.
  3. For every subsequent house further down the street, make a choice between two options: either skip this house and keep whatever total you gathered up to the previous house, or take this house and add its value to the total you had gathered from the house before last.
  4. Keep a running record of the best possible total you have accumulated as you move house by house down the street.
  5. When you reach the end of the street, the final recorded number represents the absolute maximum value you can gather without ever triggering the alarm.

Code Implementation

def rob(house_values):
    if not house_values:
        return 0

    if len(house_values) == 1:
        return house_values[0]

    maximum_loot_so_far = [0] * len(house_values)
    maximum_loot_so_far[0] = house_values[0]

    # Establish baseline best loot for the first two houses before iterating.
    maximum_loot_so_far[1] = max(house_values[0], house_values[1])

    for house_index in range(2, len(house_values)):
        # Choose between skipping current house or robbing it with past loot.
        maximum_loot_so_far[house_index] = max(
            maximum_loot_so_far[house_index - 1],
            maximum_loot_so_far[house_index - 2] + house_values[house_index]
        )

    # The final element contains the optimal solution for the entire street.
    return maximum_loot_so_far[-1]

Big(O) Analysis

Time Complexity
O(n) – As we move house by house down the street from the third house to the final property, we perform a constant amount of work at each step to make a choice between robbing the current house plus the two-houses-back total or skipping it. Given that n represents the total number of houses in the input array, we iterate through the list exactly once. This linear progression means the total operations scale directly in proportion to n, which simplifies to O(n).
Space Complexity
O(1) – To keep track of the best possible totals as we move house by house, we only need a couple of scalar variables to store the maximum values from the two preceding houses. Instead of maintaining an auxiliary array of size N to store the results for every single property along the street, we overwrite these few variables in place. Therefore, the extra memory used remains constant regardless of how many houses are on the street. Consequently, the auxiliary space complexity simplifies to O(1).

Edge Cases

Empty array of houses
How to Handle:
Return zero immediately since no money can be robbed from an empty street.
Array with a single house
How to Handle:
Return the single element's value as it is the maximum we can rob without triggering security.
Array with exactly two houses
How to Handle:
Return the maximum of the two elements since we can only rob one of them.
All houses contain zero money
How to Handle:
The algorithm will correctly compute and return zero total money robbed.
Houses with identical amounts of money
How to Handle:
The dynamic programming recurrence relation naturally evaluates alternating choices to find the optimal sum.
Very large array of houses
How to Handle:
An iterative dynamic programming approach with constant space complexity processes the input efficiently in linear time without stack overflow.
Array containing negative numbers
How to Handle:
Assuming standard constraints money is non-negative, but if present, the recurrence relation would need to ensure we can skip negative houses.
Maximum possible integer values in the array
How to Handle:
Using 64-bit integers for the DP state prevents potential integer overflow when summing large amounts.
0/75 completed