#881

Boats to Save People

Medium
ArrayTwo PointersGreedySortingTwo PointersGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

In the optimal approach, we sort the array and use a two-pointer technique. This allows us to efficiently pair the lightest and heaviest people, minimizing the number of boats needed.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the people array.
  2. 2Step 2: Initialize two pointers: one at the start (lightest) and one at the end (heaviest).
  3. 3Step 3: While the start pointer is less than or equal to the end pointer: - If the sum of the weights at both pointers is less than or equal to the limit, move both pointers inward (indicating they can share a boat). - If not, move only the end pointer inward (indicating the heavier person needs a separate boat). Step 4: Increment the boat counter each time you make a decision.
  4. 4Step 5: Return the total number of boats needed.
solution.py10 lines
1def numRescueBoats(people, limit):
2    people.sort()
3    boats = 0
4    left, right = 0, len(people) - 1
5    while left <= right:
6        if people[left] + people[right] <= limit:
7            left += 1
8        right -= 1
9        boats += 1
10    return boats

Complexity note: The sorting step takes O(n log n), and the two-pointer traversal takes O(n), making this approach efficient overall.

  • 1Sorting the array allows for efficient pairing of people.
  • 2Using two pointers minimizes the number of boats needed by always trying to pair the lightest and heaviest person.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.