15% off all plans & roadmaps Use code
See plansBoats to Save People
- LeetCode 881
- Medium
- Two Pointers
- Converging (Sorted Array Target Sum)
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^41 <= 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.
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.
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
- Keep a
usedflag for each person, all starting as unused. - Find the first unused person. If nobody is left, return 0.
- Mark that person used and try them alone, which costs 1 + solve(rest).
- For each later unused person who fits with them, mark that partner used, try 1 + solve(rest), then unmark the partner.
- 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
| Time | O(n * n!) |
|---|---|
| Space | O(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()JavaTested in our runner
import java.util.*;
class Solution {
private boolean[] used;
private int[] people;
private int limit;
public int numRescueBoats(int[] people, int limit) {
this.people = people;
this.limit = limit;
used = new boolean[people.length];
return solve();
}
private int solve() {
int i = 0;
while (i < people.length && used[i]) i++;
if (i == people.length) return 0;
used[i] = true;
int best = 1 + solve();
for (int j = i + 1; j < people.length; j++) {
if (used[j] == false && people[i] + people[j] <= limit) {
used[j] = true;
best = Math.min(best, 1 + solve());
used[j] = false;
}
}
used[i] = false;
return best;
}
}C++Tested in our runner
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
vector<bool> used(people.size(), false);
return search(people, used, limit);
}
private:
int search(vector<int>& people, vector<bool>& used, int limit) {
int n = people.size();
int i = 0;
while (i < n && used[i]) i++;
if (i == n) return 0;
used[i] = true;
int best = 1 + search(people, used, limit);
for (int j = i + 1; j < n; j++) {
if (used[j] == false && people[i] + people[j] <= limit) {
used[j] = true;
best = min(best, 1 + search(people, used, limit));
used[j] = false;
}
}
used[i] = false;
return best;
}
};JavaScriptTested in our runner
var numRescueBoats = function(people, limit) {
const n = people.length;
const used = new Array(n).fill(false);
const solve = () => {
let i = 0;
while (i < n && used[i]) i++;
if (i === n) return 0;
used[i] = true;
let best = 1 + solve();
for (let j = i + 1; j < n; j++) {
if (used[j] === false && people[i] + people[j] <= limit) {
used[j] = true;
best = Math.min(best, 1 + solve());
used[j] = false;
}
}
used[i] = false;
return best;
};
return solve();
};GoTested in our runner
func numRescueBoats(people []int, limit int) int {
n := len(people)
used := make([]bool, n)
var solve func() int
solve = func() int {
i := 0
for i < n && used[i] {
i++
}
if i == n {
return 0
}
used[i] = true
best := 1 + solve()
for j := i + 1; j < n; j++ {
if used[j] == false && people[i]+people[j] <= limit {
used[j] = true
if c := 1 + solve(); c < best {
best = c
}
used[j] = false
}
}
used[i] = false
return best
}
return solve()
}C#Tested in our runner
public class Solution {
public int numRescueBoats(int[] people, int limit) {
bool[] used = new bool[people.Length];
return Search(people, used, limit);
}
private int Search(int[] people, bool[] used, int limit) {
int n = people.Length;
int i = 0;
while (i < n && used[i]) i++;
if (i == n) return 0;
used[i] = true;
int best = 1 + Search(people, used, limit);
for (int j = i + 1; j < n; j++) {
if (used[j] == false && people[i] + people[j] <= limit) {
used[j] = true;
best = Math.Min(best, 1 + Search(people, used, limit));
used[j] = false;
}
}
used[i] = false;
return best;
}
}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 infographicSolution 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
- Sort
peoplein ascending order. - Set
leftto 0,rightto the last index, andboatsto 0. - While
leftis at mostright, check whetherpeople[left] + people[right]is at mostlimit. - If it fits, increment
left, so the lightest person boards with the heaviest. - Always decrement
rightand incrementboats. - Return
boats.
Dry run
After sorting, people = [1, 2, 2, 3] and limit = 3.
| Step | left | right | people[left] + people[right] | Fits? | Action | boats |
|---|---|---|---|---|---|---|
| 1 | 0 | 3 | 1 + 3 = 4 | No | right moves to 2 | 1 |
| 2 | 0 | 2 | 1 + 2 = 3 | Yes | left moves to 1, right moves to 1 | 2 |
| 3 | 1 | 1 | 2 + 2 = 4 | No | right moves to 0 | 3 |
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
| Time | O(n log n) |
|---|---|
| Space | O(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 boatsJavaTested in our runner
import java.util.*;
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int left = 0;
int right = people.length - 1;
int boats = 0;
while (left <= right) {
// the heaviest person always boards
if (people[left] + people[right] <= limit) {
left++;
}
right--;
boats++;
}
return boats;
}
}C++Tested in our runner
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int left = 0;
int right = (int)people.size() - 1;
int boats = 0;
while (left <= right) {
if (people[left] + people[right] <= limit) {
left++;
}
right--;
boats++;
}
return boats;
}
};JavaScriptTested in our runner
var numRescueBoats = function(people, limit) {
people.sort((a, b) => a - b);
let left = 0;
let right = people.length - 1;
let boats = 0;
while (left <= right) {
if (people[left] + people[right] <= limit) {
left++;
}
right--;
boats++;
}
return boats;
};GoTested in our runner
import "sort"
func numRescueBoats(people []int, limit int) int {
sort.Ints(people)
left, right, boats := 0, len(people)-1, 0
for left <= right {
if people[left]+people[right] <= limit {
left++
}
right--
boats++
}
return boats
}C#Tested in our runner
public class Solution {
public int numRescueBoats(int[] people, int limit) {
Array.Sort(people);
int left = 0;
int right = people.Length - 1;
int boats = 0;
while (left <= right) {
if (people[left] + people[right] <= limit) {
left++;
}
right--;
boats++;
}
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
rightonly inside theifbranch. A heavy person who cannot pair would never leave, and the loop would not end. Always decrementright, and move onlyleftconditionally. - Writing
people[left] + people[right] < limit. The limit is inclusive, so a pair that sums to exactlylimitmust 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 - binstead. - 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
Related problems
- 3Sum · same technique: Converging (Sorted Array Target Sum)
- Container With Most Water · same technique: Converging (Sorted Array Target Sum)
- Two Sum II - Input Array Is Sorted · same technique: Converging (Sorted Array Target Sum)
- 4Sum · same technique: Converging (Sorted Array Target Sum)
- 3Sum Closest · same technique: Converging (Sorted Array Target Sum)
- Trapping Rain Water · next harder, same pattern
- Sort Colors · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers