Problem 1094

Abstract / Summary

Check if a car can take all passengers from start to destination without exceeding its capacity at any time.

Note

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

Python 1094.py

class Solution:
    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
        delta = defaultdict(int)
        for t in trips:
            delta[t[1]] += t[0]
            delta[t[2]] -= t[0]

        have = 0
        for d in sorted(delta):
            have += delta[d]
            if have > capacity:
                return False
        return True
13 lines | 381 bytes | submitted September 23, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (600k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Heap (Priority Queue)
  • Prefix Sum
  • Simulation
  • Sorting
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 provided implementation determines whether a set of car-pooling trips can be accommodated within a vehicle of a given passenger capacity. It does this by converting each trip into a series of passenger count changes at specific locations, then iterating through those changes in order to track the number of passengers on board at any point. If the running total ever exceeds the vehicle’s capacity, the function returns False; otherwise it returns True after processing all locations.

Delta Map Construction

The first logical block creates a mapping from location points to the net change in passenger count that occurs at those points. For each trip, the number of passengers to be picked up is added at the start location and subtracted at the end location.

delta = defaultdict(int)
for t in trips:
    delta[t[1]] += t[0]   # pick-up at start location
    delta[t[2]] -= t[0]   # drop-off at end location

This approach collapses overlapping trips into a single structure, allowing the algorithm to consider only the moments when the passenger count actually changes.

Accumulating Passenger Count

After the delta map is built, the code iterates over the sorted location keys. By processing the locations in ascending order, the algorithm simulates the journey from the earliest pick-up point to the latest drop-off point, updating a running total of passengers on board.

have = 0
for d in sorted(delta):
    have += delta[d]
    if have > capacity:
        return False
return True

The variable have represents the current number of passengers. The early return on capacity breach ensures that the function stops as soon as an infeasible condition is detected.

Edge Cases Handled

The algorithm naturally handles trips that start and end at the same location because the net change at that point will be zero, leaving the passenger count unchanged. It also correctly processes trips that share start or end points; the cumulative delta at a shared location aggregates all pick-ups and drop-offs, preserving the correct passenger total. Situations where the list of trips is empty are covered as the loop over sorted(delta) simply does not execute, and the function returns True because no capacity violation can occur.

Performance Optimizations

The use of a defaultdict(int) for the delta map eliminates the need for explicit existence checks when updating counts, reducing overhead in the construction phase. By storing only the points where changes occur, the algorithm avoids iterating over every possible location between the minimum and maximum stops, which could be large. Sorting the keys of the delta map is the only operation that introduces ordering, and it operates on a set whose size is bounded by twice the number of trips (each trip contributes at most two distinct points). The early exit on capacity overflow prevents unnecessary processing of remaining locations once a violation is found, further improving runtime in worst-case scenarios where the capacity is exceeded early.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big bus going on a long road trip. Some passengers get on at certain stops and get off at other stops. The code keeps track of how many people are on the bus at any moment.

First, the computer looks at every journey in the list. When a group of people starts their trip, it adds them to a tally for that stop. When that same group reaches their destination, it subtracts them from the tally because they leave the bus.

After noting all the changes at every stop, the computer lines up all the stops in order from the very beginning to the very end. It goes to the first stop and checks how many passengers are on board. It continues to the next stop, adding the people who just got on and taking away the people who just got off.

At every stop along the way, the computer checks to see if there are too many people sitting on the bus. If the number of passengers is bigger than the number of seats available, the bus is too crowded.

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 = 8 | μ = 8.30 | σ = 1.21

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++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python JS Java C# Go Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
32 links | 19 authors | 8 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

21 solutions   September 23, 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