Boats to Save People — LeetCode 881 Python Solution

MediumGreedyArrayTwo PointersSorting
Problem
#881
Reading time
2 min

The problem

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.

Example

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

Python solution

Python
class Solution:
    def numRescueBoats(self, people: List[int], limit: int) -> int:
        people.sort()
        ans = 0
        i, j = 0, len(people) - 1
        while i <= j:
            if people[i] + people[j] <= limit:
                i += 1
            j -= 1
            ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 881. Boats to Save People is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 881. Boats to Save People?
LeetCode 881. Boats to Save People is rated Medium on LeetCode.
What is the time complexity of LeetCode 881. Boats to Save People?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 881. Boats to Save People?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 881. Boats to Save People cover?
LeetCode 881. Boats to Save People is tagged Greedy, Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview