Boats to Save People - Problem

Imagine you're coordinating a rescue operation at sea! You have an unlimited number of rescue boats, but each boat can only carry a maximum of 2 people and has a strict weight limit.

Given an array people where people[i] represents the weight of the i-th person, and each boat can carry a maximum weight of limit, your mission is to find the minimum number of boats needed to rescue everyone.

Key constraints:
• Each boat carries at most 2 people
• The combined weight must not exceed the limit
• You want to minimize the total number of boats used

Example: If people weigh [1,2] and limit is 3, you need only 1 boat since 1+2=3 ≤ limit.

Input & Output

example_1.py — Basic Case
$ Input: people = [1,2], limit = 3
Output: 1
💡 Note: Both people can fit in one boat since 1 + 2 = 3 ≤ 3 (limit). Only 1 boat needed.
example_2.py — Multiple Boats
$ Input: people = [3,2,2,1], limit = 3
Output: 3
💡 Note: After sorting: [1,2,2,3]. Boat 1: [1,2], Boat 2: [2] (can't pair with 3), Boat 3: [3]. Total: 3 boats.
example_3.py — All Alone
$ Input: people = [3,5,3,4], limit = 5
Output: 4
💡 Note: After sorting: [3,3,4,5]. No two people can share a boat (minimum sum is 3+3=6 > 5), so each needs their own boat.

Visualization

Tap to expand
🚤 Rescue Boat OptimizationGreedy Strategy: Pair lightest with heaviestInitial State: people = [1, 2, 4, 5], limit = 61245LEFTRIGHTStep 1: Check 1 + 5 = 66 ≤ 6 ✓ (within limit)🚤 Boat 1[1, 5]Move both pointers inwardStep 2: Check 2 + 4 = 66 ≤ 6 ✓ (within limit)🚤 Boat 2[2, 4]Pointers crossed - done!🎯 Final Result: 2 boatsOptimal greedy strategy pairs people efficientlyTime: O(n log n), Space: O(1)
Understanding the Visualization
1
Sort people by weight
Arrange from lightest to heaviest for optimal pairing
2
Use two pointers
Left at lightest, right at heaviest person
3
Apply greedy strategy
If lightest + heaviest ≤ limit, pair them. Otherwise heaviest goes alone
4
Continue until done
Move pointers inward and repeat until everyone is rescued
Key Takeaway
🎯 Key Insight: The greedy strategy works because if the lightest person can't pair with the heaviest, then no one else can pair with the heaviest either (since everyone else is heavier than the lightest person).

Time & Space Complexity

Time Complexity
⏱️
O(n log n)

Dominated by sorting the array. The two-pointer traversal is O(n)

n
2n
Linearithmic
Space Complexity
O(1)

Only uses constant extra space for pointers and variables (excluding sorting space)

n
2n
Linear Space

Constraints

  • 1 ≤ people.length ≤ 5 × 104
  • 1 ≤ people[i] ≤ limit ≤ 3 × 104
  • Each boat carries at most 2 people
  • Total weight in boat must not exceed limit
Asked in
Amazon 45 Google 32 Microsoft 28 Facebook 24
38.9K Views
High Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen