Taro Logo

Boats to Save People

#139 Most AskedMedium
Topics:
ArraysTwo PointersGreedy Algorithms

You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.

Return the minimum number of boats to carry every given person.

Example 1:

Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)

Example 2:

Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)

Example 3:

Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)

Constraints:

  • 1 <= people.length <= 5 * 104
  • 1 <= people[i] <= limit <= 3 * 104

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 are the constraints on the length of the people array and the maximum weight capacity limit?
  2. Can an individual person's weight ever exceed the maximum weight capacity of a boat?
  3. Are there any duplicate weights in the input array, and how should identical weights be handled?
  4. What should be returned if the input array of people is empty?
  5. Is it guaranteed that every person can be successfully carried by the boats given the constraints?

Brute Force Solution

Approach

Imagine you have a group of people with different weights and a fleet of rescue boats that can each hold a maximum weight limit. The brute force approach tries every possible combination of pairing people up and putting them into boats to find the absolute minimum number of boats needed.

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

  1. Start by looking at the entire group of people and all the available boats.
  2. Try every conceivable way to group the people together, making sure no boat holds more than two people and their combined weight stays under the boat limit.
  3. For each grouping you try, count how many boats are needed to rescue everyone.
  4. If a particular grouping fails because a boat is overloaded, discard that combination and move on.
  5. Keep track of the total number of boats used in every successful combination.
  6. Repeat this trial-and-error process for every possible arrangement of people sharing boats.
  7. Finally, look back at all the successful counts you recorded and pick the smallest one as your final answer.

Code Implementation

def num_rescue_boats(people_weights, weight_limit):
    minimum_boats_needed = len(people_weights)

    # Explore all partition combinations since brute force requires testing every possible grouping
    def generate_groupings(person_index, current_groupings):
        nonlocal minimum_boats_needed
        if person_index == len(people_weights):
            valid_grouping = True
            for boat in current_groupings:
                if sum(boat) > weight_limit or len(boat) > 2:
                    valid_grouping = False
                    break
            if valid_grouping:
                minimum_boats_needed = min(minimum_boats_needed, len(current_groupings))
            return

        for group_index in range(len(current_groupings)):
            current_groupings[group_index].append(people_weights[person_index])
            generate_groupings(person_index + 1, current_groupings)
            current_groupings[group_index].pop()

        current_groupings.append([people_weights[person_index]])
        generate_groupings(person_index + 1, current_groupings)
        current_groupings.pop()

    generate_groupings(0, [])

    # Return the smallest count recorded from all valid trials
    return minimum_boats_needed

Big(O) Analysis

Time Complexity
O(2^n) – The brute force approach attempts to evaluate every conceivable grouping and pairing of n people into boats to find the absolute minimum. For each person, we must explore exponential combinations of whether they share a boat with someone else or ride alone. This trial-and-error process across all possible arrangements leads to approximately 2 to the power of n operations. Simplifying this exponential growth results in an overall time complexity of O(2^n).
Space Complexity
O(2^N) – The brute force trial-and-error approach requires tracking every conceivable way to group the people and all successful combinations of boat counts. As the input size N increases, the recursive exploration of pairing combinations and storing intermediate trial results demands exponential extra memory. Therefore, the auxiliary space complexity grows exponentially relative to the number of people, resulting in O(2^N) space.

Optimal Solution

Approach

To save the most boats, the optimal strategy pairs the heaviest person possible with the lightest available person if they can share a boat together. By organizing the people from lightest to heaviest, we can make greedy pairings from the extremes inward, ensuring every boat is used as efficiently as possible.

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

  1. Line up everyone in order from the lightest person to the heaviest person.
  2. Send the heaviest person to the front of the line and look at the lightest person remaining.
  3. Check if the heaviest person and this lightest person can safely fit together in the same boat without exceeding the weight limit.
  4. If they both fit together, put them in the same boat and cross both of them off your list.
  5. If they are too heavy to share, the heaviest person must take a boat all by themselves, so just cross the heaviest person off your list and leave the lightest person for a future boat.
  6. Repeat this pairing process from both ends of the line inward until everyone has been assigned to a boat.

Code Implementation

class Solution:
    def num_rescue_boats(self, people_weights: list[int], weight_limit: int) -> int:
        people_weights.sort()
        
        lightest_person_index = 0
        heaviest_person_index = len(people_weights) - 1
        total_boats_needed = 0
        
        # Sorting allows us to greedily pair extremes, optimizing boat capacity usage.
        while lightest_person_index <= heaviest_person_index:
            
            if people_weights[lightest_person_index] + people_weights[heaviest_person_index] <= weight_limit:
                lightest_person_index += 1
            
            # The heaviest person always needs a boat, sharing with the lightest if possible.
            heaviest_person_index -= 1
            total_boats_needed += 1
            
        # Every person accounted for ensures minimum boats are used to safely transport everyone.
        return total_boats_needed

Big(O) Analysis

Time Complexity
O(n log n) – The primary driver of the cost is sorting the input array of size n from lightest to heaviest, which takes O(n log n) time. Afterward, the two-pointer approach scans the array from both ends inward, visiting each of the n elements at most once in linear O(n) time. Combining the sorting and the single-pass traversal, the total operations approximate n log n plus n, which simplifies to the final Big O of O(n log n).
Space Complexity
O(n) – To execute the strategy of lining up everyone in order from lightest to heaviest, the algorithm requires sorting the input data. Depending on the underlying sorting implementation, the sorting process utilizes an auxiliary space that scales linearly with N, where N is the total number of people. Beyond the pointers used to track the extremes of the sorted list, no additional data structures grow with the input size. Therefore, the extra memory required is dominated by the sorting overhead, resulting in an auxiliary space complexity of O(n).

Edge Cases

Single person in the array
How to Handle:
Sorting and the two-pointer approach naturally process the single element, requiring exactly one boat.
Person weight exactly equals the boat limit
How to Handle:
The greedy approach correctly assigns them to their own individual boat since they cannot be paired with anyone else.
Two people whose combined weight is less than or equal to the limit
How to Handle:
The pointers at both ends will successfully pair them together into a single boat.
Two people whose combined weight strictly exceeds the limit
How to Handle:
The heavier person pointer moves inward to take their own boat while the lighter person waits for a smaller match.
All people weigh more than half the limit but less than the limit
How to Handle:
No two people can share a boat, so the algorithm correctly allocates one boat per person.
Large input size with up to fifty thousand elements
How to Handle:
The O(n log n) sorting plus O(n) two-pointer traversal scales efficiently well within time limits.
Extreme weight disparity between the lightest and heaviest individuals
How to Handle:
The greedy strategy optimally pairs the lightest person with the heaviest person whenever their sum fits.
Weights containing many duplicate values
How to Handle:
Sorting groups duplicates together and the linear scan correctly pairs them without index collision issues.
0/245 completed