Boats to Save People

Medium Arrays & Hashing Two Pointer Original on LeetCode

Boats to Save People is a medium arrays & hashing problem solved with the two pointer pattern. The best approach, optimal (sort + two pointers), runs in O(n log n) time and O(1) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (scan for the lightest partner) up.

Problem

You are given an array people where people[i] is the weight of the i-th person, and an integer limit. There are unlimited boats, and every boat can carry at most two people as long as their combined weight is at most limit.

No single person is heavier than limit. Return the minimum number of boats needed to carry everyone.

Examples

Example 1

Input
people = [4, 1, 3, 2], limit = 5
Output
2
Why
Pair 4 with 1 and 3 with 2; both boats carry exactly 5.

Example 2

Input
people = [6, 2, 5, 4], limit = 7
Output
3
Why
Only 5 + 2 fits together; 6 and 4 each need a boat of their own.

Example 3

Input
people = [3, 3, 3], limit = 3
Output
3
Why
Every person already reaches the limit alone.

Constraints

  • 1 <= people.length <= 5 * 10^4
  • 1 <= people[i] <= limit <= 3 * 10^4

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (scan for the lightest partner)O(n²)O(n)
Optimal (sort + two pointers)O(n log n)O(1)

1Brute force (scan for the lightest partner)

TimeO(n²)Each of the n boats may scan the array from the start.
SpaceO(n)One boolean per person.

Sort the weights. Repeatedly take the heaviest person still on shore, scan for the lightest person still on shore, and put them in the same boat if they fit. Each boat removes one or two people; each scan is linear.

  1. Sort people ascending; mark everyone as not yet boarded.
  2. For i from n - 1 down to 0, skip boarded people; otherwise board i and use one boat.
  3. Scan j from 0 upward for the first person not boarded (j < i); if people[i] + people[j] <= limit, board j as well.
class Solution {
    public int numRescueBoats(int[] people, int limit) {
        Arrays.sort(people);
        int n = people.length;
        boolean[] boarded = new boolean[n];
        int boats = 0;
        for (int i = n - 1; i >= 0; i--) {
            if (boarded[i]) continue;
            boarded[i] = true;
            boats++;
            for (int j = 0; j < i; j++) {
                if (!boarded[j]) {
                    if (people[i] + people[j] <= limit) boarded[j] = true;
                    break;
                }
            }
        }
        return boats;
    }
}

2Optimal (sort + two pointers)

TimeO(n log n)Sorting dominates; the two-pointer sweep is O(n).
SpaceO(1)Only two pointers besides the sort's own work.

After sorting, the lightest unboarded person is always at lo and the heaviest at hi. The heaviest person always takes a boat; if the lightest fits alongside, they share it. Pairing the heaviest with the lightest is never worse: if the lightest cannot ride with the heaviest, nobody can.

  1. Sort people; lo = 0, hi = n - 1, boats = 0.
  2. While lo <= hi: if people[lo] + people[hi] <= limit, lo++.
  3. hi--, boats++.
  4. Return boats.
class Solution {
    public int numRescueBoats(int[] people, int limit) {
        Arrays.sort(people);
        int lo = 0, hi = people.length - 1, boats = 0;
        while (lo <= hi) {
            if (people[lo] + people[hi] <= limit) lo++;
            hi--;
            boats++;
        }
        return boats;
    }
}

Edge cases to test

  • A single person needs exactly one boat
  • Everyone weighs exactly the limit, so nobody can share
  • Everyone is light enough that all can be paired
  • Many equal weights

Hints

Hint 1

A boat holds at most two people, so the question is how many pairs you can form. Who is the hardest person to place?

Hint 2

The heaviest person must ride with someone light, if anyone. Which partner gives the best chance: the lightest remaining person.

Hint 3

Sort the weights and use one pointer at the light end and one at the heavy end.

FAQ

What is the best time complexity for Boats to Save People?

Optimal (sort + two pointers) runs in O(n log n) time and O(1) extra space. Sorting dominates; the two-pointer sweep is O(n).

Which pattern does Boats to Save People use?

It is a arrays & hashing problem that uses the two pointer pattern. Other problems with the same pattern: Two Sum II - Input Array Is Sorted, Valid Triangle Number, Container With Most Water.

Is there a brute force solution for Boats to Save People?

Yes. Brute force (scan for the lightest partner) takes O(n²) time and O(n) space. Sort the weights.

Which edge cases should I test for Boats to Save People?

A single person needs exactly one boat; Everyone weighs exactly the limit, so nobody can share; Everyone is light enough that all can be paired; Many equal weights.