Car Pooling — LeetCode 1094 Python Solution

MediumArrayPrefix SumSortingSimulationHeap (Priority Queue)
Problem
#1094
Pattern
Prefix Sum
Reading time
2 min

The problem

There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).

Example

Input
trips = [[2,1,5],[3,3,7]], capacity = 4
Output
false

Python solution

Python
class Solution:
    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
        mx = max(e[2] for e in trips)
        d = [0] * (mx + 1)
        for x, f, t in trips:
            d[f] += x
            d[t] -= x
        return all(s <= capacity for s in accumulate(d))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(M) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1094. Car Pooling is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1094. Car Pooling?
LeetCode 1094. Car Pooling is rated Medium on LeetCode.
What is the time complexity of LeetCode 1094. Car Pooling?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1094. Car Pooling?
The Python solution on this page uses O(M) auxiliary space.
What topics does LeetCode 1094. Car Pooling cover?
LeetCode 1094. Car Pooling is tagged Array, Prefix Sum, Sorting, Simulation and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview