Problem 881

Abstract / Summary

People must be paired to cross a river using boats with weight limits, minimizing the number of trips needed.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0881.py

class Solution:
    def numRescueBoats(self, people: List[int], limit: int) -> int:
        over  = [] # boats with 1 person weighting more than 50% of limit
        under = [] # everybody else

        for p in people:
            if p > limit / 2:
                over .append(p)
            else:
                under.append(p)

        # match last elements
        over .sort(reverse = True)
        under.sort()

        result = 0
        while over and under:
            if over[-1] + under[-1] <= limit:
                # new boat
                result += 1
                over .pop()
                under.pop()
            else:
                # too heavy if merged, move person
                over .append(under.pop())

        # left-overs
        result += len(over)
        result += (len(under) + 1) // 2 # share boats
        return result
30 lines | 893 bytes | submitted November 3, 2023 | GitHub   31% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 62% (900k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the classic “minimum number of boats” problem. It separates passengers into two groups based on whether an individual’s weight exceeds half of the boat limit. The algorithm then greedily pairs the heaviest “over-half” passenger with the lightest “under-half” passenger, counting a boat each time a feasible pair is found. Remaining passengers are accounted for with simple arithmetic that reflects the fact that any two “under-half” passengers can share a boat while each “over-half” passenger must travel alone.

Key Steps

Partitioning the input

The first loop iterates over the list of passenger weights and distributes each weight into one of two collections.

over  = []  # boats with 1 person weighting more than 50% of limit
under = []  # everybody else

for p in people:
    if p > limit / 2:
        over .append(p)
    else:
        under.append(p)

The condition p > limit / 2 isolates passengers that cannot be paired with any other passenger without exceeding the limit, because any additional weight would push the total above the capacity.

Sorting for greedy pairing

Both collections are sorted to enable efficient access to the extremes needed for the greedy step.

over .sort(reverse = True)   # heaviest first, but later accessed from the end
under.sort()                 # lightest first

Sorting the “over” list in descending order and then using pop() from the end yields the smallest element of that list, which is the lightest “over-half” passenger still unpaired. The “under” list is sorted ascending so that pop() also yields the heaviest remaining “under-half” passenger.

Greedy matching loop

The core loop runs while both groups contain passengers. It attempts to pair the lightest “over-half” passenger with the heaviest “under-half” passenger.

result = 0
while over and under:
    if over[-1] + under[-1] <= limit:
        # new boat
        result += 1
        over .pop()
        under.pop()
    else:
        # too heavy if merged, move person
        over .append(under.pop())

If the combined weight does not exceed the limit, a boat is allocated and both passengers are removed. When the sum is too large, the heaviest “under-half” passenger cannot share a boat with the current lightest “over-half” passenger, so that “under-half” passenger is moved to the “over” list. This effectively treats the passenger as a solo traveler for subsequent iterations.

Accounting for leftovers

After the greedy loop finishes, any remaining “over-half” passengers each require their own boat, and the remaining “under-half” passengers can be paired two-by-two.

result += len(over)
result += (len(under) + 1) // 2   # share boats
return result

The integer division (len(under) + 1) // 2 automatically rounds up, handling the case where an odd number of “under-half” passengers leaves one passenger without a partner.

Edge Cases Handled

When every passenger’s weight is greater than half the limit, the initial partition places all weights into the over list. The greedy loop never executes because under is empty, and the final addition of len(over) correctly returns the number of passengers as the number of boats.

If all passengers weigh exactly half the limit, they are placed in the under list. The greedy loop does not run because over is empty, and the final arithmetic (len(under) + 1) // 2 correctly computes the minimum number of boats by pairing each two passengers together.

When the input list is empty, both over and under remain empty, the while loop is skipped, and the final result is zero, which is the correct answer.

If the limit is very large relative to all passenger weights, every passenger ends up in under. The final division groups them into the smallest possible number of boats, handling both even and odd counts without special casing.

When a single passenger’s weight equals the limit, the condition p > limit / 2 puts the passenger into over. The algorithm then counts that passenger as a solo boat via len(over), satisfying the constraint that no boat may exceed the limit.

Performance Optimizations

The algorithm reduces the search space early by separating passengers that are guaranteed to travel alone. This eliminates unnecessary pair checks for those weights.

Sorting both groups once enables constant-time access to the smallest “over-half” and largest “under-half” elements, avoiding repeated scans. The use of pop() on the end of the list is an O(1) operation, ensuring that each removal or addition does not incur additional overhead.

The while loop moves a passenger from under to over only when a pairing is impossible, which prevents futile pairing attempts and quickly converges to the final state.

Finally, the leftover counting step uses simple arithmetic on the lengths of the two lists, avoiding any further iteration over the remaining elements. This makes the overall processing linear after the initial sort.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a big group of people who want to go on a boat ride, but the boat has a strict weight limit. To make sure everyone gets a turn, the code first sorts the people into two piles. One pile is for the heavier people who take up more than half of the weight limit, and the other pile is for the lighter people.

Once everyone is in a pile, the code looks at the heaviest person left and tries to see if the lightest person can fit on the same boat with them. If the two of them together do not weigh too much, they both get on the boat happily. If they are too heavy, that big person has to go on their own boat, and the person who was moved into the heavy pile waits for a different turn.

Finally, the code counts up all the boats used. If there are any people left over who still do not have a ride, it counts how many extra boats are needed to carry them safely until everyone has had a chance to enjoy the water.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 5.30 | σ = 1.70

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
martianoff Scala
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
martianoff Scala
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
38 links | 25 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

13 solutions   November 3, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality