◀ THE GRIND — TWO POINTERS

Boats to Save People

MEDIUM✓ CHIP-TIMEDLC #881 — FULL STATEMENT ↗

The drill: Ferry everyone across using boats that each carry at most two people under a fixed weight limit; find the fewest boats needed to move every person.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A group of people, each with their own weight, needs ferrying across using boats that hold at most two people and never exceed a fixed weight limit per trip.

Every boat that leaves counts against the total, whether it carries one person or two, and every person must eventually be moved — nobody is left behind.

The goal is the fewest boats that get everyone across, not the assignment of who rides with whom.

EX 01
people = [1, 2] · limit = 3
1
MINIMUM SIZE, BOTH FIT ONE BOAT
EX 02
people = [3, 2, 2, 1] · limit = 3
3
ONLY THE TWO LIGHTEST CAN SHARE
EX 03
people = [3, 5, 3, 4] · limit = 5
4
NOBODY CAN PAIR, EVERY BOAT RIDES ALONE
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Every boat should carry the heaviest person still waiting, since nobody else is harder to place. Who, if anyone, should ride along with them?

HINT 2 THE STRUCTURE

Sort by weight. The heaviest person left is the hardest to pair; check whether the lightest person left can share a boat with them.

HINT 3 ONE STEP FROM THE ANSWER

Two pointers from both ends of the sorted array: the heaviest always boards. The lightest joins them only if the pair still fits the limit — otherwise the lightest waits for a future boat. Either way, the boat leaves and both pointers move one step closer.

COACH'S BOARD — THE PATTERN, STEP BY STEP
HEAVIEST PLUS LIGHTESTPATTERN · TWO POINTERS FROM BOTH ENDSpeople = [1, 2, 3, 4, 5] (sorted) · limit = 6
1
2
3
4
5
BOATS LAUNCHED
— empty —
STEP 1

Limit 6. Heaviest and lightest pair up from sorted ends: L=0 (1kg), R=4 (5kg).

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/boats-to-save-people.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def numRescueBoats(self, people: List[int], limit: int) -> int:
        people = sorted(people)
        l, r = 0, len(people) - 1
        boats = 0
        while l <= r:
            if people[l] + people[r] <= limit:
                l += 1
            r -= 1
            boats += 1
        return boats
TIME O(N LOG N)SPACE O(1)PYTHON · RACE PACE · 11 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED