15% off all plans & roadmaps Use code

See plans

Boats to Save People

Updated

TL;DR: You pack people into boats that carry at most two people and a weight limit, and you want the fewest boats. Sort the weights, then pair the heaviest person with the lightest whenever their total fits, and send the heaviest alone otherwise.

Problem

You are given an array people, where people[i] is the weight of the ith person. You also have an unlimited number of boats, and each boat can carry a maximum weight of limit. A boat holds at most two people, and only when their combined weight is at most limit.

Return the minimum number of boats needed to carry every 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 * 10^4
  • 1 <= people[i] <= limit <= 3 * 10^4

Constraints that matter

  • n can be 5 * 10^4, so checking every pair (about 1.25 * 10^9 pairs) is too slow. The solution needs a sort or a single linear pass.
  • Each boat holds at most two people, so no boat takes three. The answer is at least n / 2 and never more than n.
  • Since people[i] is at most limit, every person fits alone. One boat per person is always a valid answer, so the answer never exceeds n.
  • Weights up to 3 * 10^4 keep any pair sum under 6 * 10^4, so plain int arithmetic is safe in every language.

View on LeetCode

Hints

Hint 1

This is a greedy problem on a sorted array, and it fits the converging two pointers pattern.

Hint 2

Try every way to seat people.

Solution

Intuition

This is a greedy problem on a sorted array, and it fits the converging two pointers pattern. Each boat holds at most two people, so the heaviest person always needs a boat. The only real choice is whether that boat also carries a partner.

Picture a ferry queue sorted from lightest at the left end to heaviest at the right end. The right pointer is the heaviest person, who always boards, and the left pointer is the lightest person, who joins only if the pair fits.

Sorting makes that choice forced. If the heaviest person cannot share with the lightest person, nobody can, because everyone else weighs at least as much as the lightest. So the heaviest rides alone. If they do fit, pairing them is safe, since an exchange argument shows some optimal packing puts them together.

The two pointers track the lightest and heaviest people still waiting. Each step seats the heaviest person, and seats the lightest too when the pair fits. Because the heaviest person always leaves the range, the loop runs at most n times.

Watch the pattern animation

Worked example

Input: people = [3, 2, 2, 1], limit = 3
Output: 3
Explanation: Sorted, the weights become [1, 2, 2, 3]. The heaviest person (3) cannot share with anyone, so they ride alone. The lightest person (1) then shares a boat with a 2, and the last 2 rides alone. That makes 3 boats.

Approach 1: Brute force (exhaustive search)

Try every way to seat people. Take the first person still waiting. They either ride alone, or they share a boat with any other waiting person whose weight keeps the pair within limit. Try each option, solve the rest the same way, and keep the smallest boat count.

This is correct because the first waiting person must board somewhere, so every valid packing is covered. It only finishes on small inputs, because each branch repeats the same search over the people who remain.

Steps

  1. Keep a used flag for each person, all starting as unused.
  2. Find the first unused person. If nobody is left, return 0.
  3. Mark that person used and try them alone, which costs 1 + solve(rest).
  4. For each later unused person who fits with them, mark that partner used, try 1 + solve(rest), then unmark the partner.
  5. Unmark the first person and return the smallest count found.

Dry run

Use the page example in its original order, [3, 2, 2, 1], with limit 3. The first waiting person is 3.

  • 3 has no partner. 3 + 2 = 5 and 3 + 1 = 4 both exceed 3, so 3 rides alone. That is 1 boat.
  • Remaining [2, 2, 1]. The first 2 pairs with 1, since 2 + 1 = 3 fits. That leaves [2], which rides alone.
  • Boats for [2, 2, 1] are 2, so the total is 1 + 2 = 3.

The only option for 3 was alone, so the search returns 3, which matches the expected output.

Complexity

TimeO(n * n!)
SpaceO(n)

Let n be the number of people. Every call picks the first unused person and tries at most n - 1 partners, so each call does O(n) work. The search tree has one leaf for each way to split people into boats of size one or two, and there are at most n factorial such splits, so the total work is O(n * n factorial). Recursion depth is at most n, and the used flags take n cells, so the extra space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def numRescueBoats(self, people: List[int], limit: int) -> int:
        n = len(people)
        used = [False] * n

        def solve() -> int:
            # find the first person who has not been seated yet
            i = 0
            while i < n and used[i]:
                i += 1
            if i == n:
                return 0
            used[i] = True
            best = 1 + solve()  # person i rides alone
            for j in range(i + 1, n):
                if not used[j] and people[i] + people[j] <= limit:
                    used[j] = True
                    best = min(best, 1 + solve())
                    used[j] = False
            used[i] = False
            return best

        return solve()

The Converging (Sorted Array Target Sum) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Converging (Sorted Array Target Sum)

Part of Two Pointers

Approach 2: Sort, then two pointersOptimalConverging (Sorted Array Target Sum)

What's slow in the brute force is that it tries every partner for every person and never uses the order of the weights. Sorting fixes that. After sorting, the heaviest person sits at the right end and the lightest at the left. The heaviest person must board, so the only decision is whether the lightest can join them.

If the pair fits, both leave the waiting line and one boat is counted. If it does not fit, the heaviest leaves alone and one boat is counted. Either way the heaviest person is seated, with one check per boat and no search.

Steps

  1. Sort people in ascending order.
  2. Set left to 0, right to the last index, and boats to 0.
  3. While left is at most right, check whether people[left] + people[right] is at most limit.
  4. If it fits, increment left, so the lightest person boards with the heaviest.
  5. Always decrement right and increment boats.
  6. Return boats.

Dry run

After sorting, people = [1, 2, 2, 3] and limit = 3.

Stepleftrightpeople[left] + people[right]Fits?Actionboats
1031 + 3 = 4Noright moves to 21
2021 + 2 = 3Yesleft moves to 1, right moves to 12
3112 + 2 = 4Noright moves to 03

In row 3, left equals right, so the check compares one person with themselves. That person boards one boat either way, and the loop then ends. The loop stops because left (1) is greater than right (0). The function returns 3, which matches the brute force.

Complexity

TimeO(n log n)
SpaceO(1) extra for the pointers, plus the sort's working memory (O(log n) for quicksort-style sorts, up to O(n) for Python's Timsort)

Let n be the number of people. Sorting takes O(n log n) comparisons, and that dominates the total time. The loop starts with right at n - 1 and decreases right on every pass, so it runs at most n times with O(1) work each, which is O(n). Total time is O(n log n), and the pointers and counter add only O(1) memory.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def numRescueBoats(self, people: List[int], limit: int) -> int:
        people.sort()  # ascending weights
        left, right = 0, len(people) - 1
        boats = 0
        while left <= right:
            # the heaviest person always boards; the lightest joins if the pair fits
            if people[left] + people[right] <= limit:
                left += 1
            right -= 1
            boats += 1
        return boats

Common mistakes

  • Running the loop before sort. The greedy choice depends on the heaviest and lightest people sitting at the ends, so sort first.
  • Moving right only inside the if branch. A heavy person who cannot pair would never leave, and the loop would not end. Always decrement right, and move only left conditionally.
  • Writing people[left] + people[right] < limit. The limit is inclusive, so a pair that sums to exactly limit must share a boat. Use <=.
  • Calling people.sort() in JavaScript with no comparator. It sorts as strings, so 10 comes before 9. Pass (a, b) => a - b instead.
  • Letting a boat take three people because their total fits. The rule is at most two people per boat, so each boat counts at most two.
  • Scanning the whole list for the heaviest partner that fits, for every boat. That makes the solution O(n^2) or worse. The two-pointer walk finds the same pairs in one pass.

Edge cases

  • One person, such as [5] with limit 5. The answer is 1, and the loop handles left equal to right correctly.
  • Every weight equals limit, such as [3, 3, 3] with limit 3. No pair fits, so the answer is 3.
  • Every pair fits, such as [1, 1, 1, 1] with limit 2. The answer is 2, which is n / 2.
  • The lightest pairs with a middle person, such as [1, 4, 4, 5] with limit 5. Sorted, 1 + 5 is too big, so 5 rides alone. Then 1 pairs with a 4, and the last 4 rides alone. The answer is 3.
  • Maximum size, such as 50000 people who all weigh 1 with limit 30000. Every pair fits, so the answer is 25000.

Follow-ups interviewers ask

What if the input is already sorted?
Skip the sort. The two-pointer pass alone runs in O(n) time with O(1) extra space. The sort was the only step that cost O(n log n).
Can you do it in O(1) extra space?
The pointers and counter already use O(1). Java and C++ sorts use O(log n) stack in typical implementations, so I would choose heapsort, which sorts in place with O(1) extra space and O(n log n) time. That trades some speed in practice for the memory bound.
What if you cannot modify the input array?
Copy the array first, which costs O(n) extra memory, and sort the copy. The rest of the algorithm stays the same. Because weights are at most 3 * 10^4, a counting sort over a count array of size limit + 1 also works in O(n + limit) time.

Boats to Save People FAQ

What is the time complexity of Boats to Save People?

The solution runs in O(n log n) time because sorting dominates. The two-pointer loop after sorting takes O(n). Space is O(1) for the pointers, plus the sort's own working memory.

Why use two pointers for Boats to Save People?

After sorting, the heaviest and lightest people sit at the ends. Each step decides about the heaviest person, and the lightest joins only when the pair fits. Two pointers make each decision in O(1) with no search.

Can Boats to Save People be solved in O(1) extra space?

Yes, if you use an in-place sort with O(1) auxiliary memory, such as heapsort. The greedy pass itself needs only two indices and a counter. Java and C++ quicksort-style sorts use O(log n) stack, so the answer depends on the sort you pick.

Why does pairing the heaviest person with the lightest work?

If the lightest person cannot pair with the heaviest, nobody can. If they can pair, an exchange argument shows some optimal packing contains that pair. So the greedy move never blocks the best answer.

Does Python's sort change the input list in Boats to Save People?

Yes. people.sort() sorts the caller's list in place. If you must keep the original order, use sorted(people), which returns a new list and costs O(n) extra memory.

Asked at

See which companies ask this — Pro

Practise it