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
Difficulty
and has an acceptance rate of about 62% (900k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Sorting
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 1317: Convert Integer to the Sum of Two No-Zero Integers
- problem 1417: Reformat The String
- problem 1556: Thousand Separator
- problem 1790: Check if One String Swap Can Make Strings Equal
- problem 2259: Remove Digit From Number to Maximize Result
- problem 2582: Pass the Pillow
- problem 2605: Form Smallest Number From Two Digit Arrays
- problem 2729: Check if The Number is Fascinating
- problem 1503: Last Moment Before All Ants Fall Out of a Plank
- problem 1578: Minimum Time to Make Rope Colorful
- problem 1685: Sum of Absolute Differences in a Sorted Array
- problem 1701: Average Waiting Time
Extra
- 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