Skip to content

Commit 083ee03

Browse files
authored
Merge pull request #132 from BrianLusina/feat/algorithms-intervals-car-pooling
feat(algorithms, intervals): car pooling
2 parents dd14168 + 5aece96 commit 083ee03

19 files changed

+193
-0
lines changed

DIRECTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,8 @@
106106
* [Decoding](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/huffman/decoding.py)
107107
* [Encoding](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/huffman/encoding.py)
108108
* Intervals
109+
* Car Pooling
110+
* [Test Car Pooling](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/intervals/car_pooling/test_car_pooling.py)
109111
* Count Days
110112
* [Test Count Days Without Meetings](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/intervals/count_days/test_count_days_without_meetings.py)
111113
* Full Bloom Flowers
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# Car Pooling
2+
3+
You are given a car with a fixed number of seats, denoted by an integer capacity. The car only travels in one direction
4+
— eastward — and does not make any U-turns.
5+
6+
You are also provided with an array, trips, where each element trips[i]= [numPassengersi, fromi, toi] represents a group of
7+
numPassengersi that must be picked up at location fromi and dropped off at location toi . All locations are measured in
8+
kilometers east of the starting point.
9+
10+
Your task is to determine whether it is possible to complete all the trips without exceeding the car’s capacity at any
11+
point in time.
12+
13+
Return TRUE if all trips can be completed successfully, or FALSE otherwise.
14+
15+
## Constraints
16+
17+
- 1 <= `trips.length` <= 1000
18+
- `trips[i].length` == 3
19+
- 1 <= `numPassengers` <= 1000
20+
- 0 <= fromi < toi <= 1000
21+
- 1 <= `capacity` <= 10^5
22+
23+
## Examples
24+
25+
![Example 1](./images/examples/car_pooling_example_1.png)
26+
![Example 2](./images/examples/car_pooling_example_2.png)
27+
![Example 3](./images/examples/car_pooling_example_3.png)
28+
29+
30+
## Solution
31+
32+
The core intuition behind this solution is to simulate the journey of the car using a timeline, tracking when passengers
33+
get in and get out. This approach aligns with the merge intervals pattern, where we focus on events happening at specific
34+
points in time, rather than handling each trip separately in isolation. The idea is to accumulate and monitor the number
35+
of passengers in the car at any moment using a difference array (also known as a prefix sum technique).
36+
37+
In the context of this problem, each trip defines a passenger change over a specific interval — passengers are picked up
38+
at from and dropped off at to. Instead of iterating over the entire interval (which is inefficient), we can track just
39+
the start and end of the interval using a fixed-size timeline array.
40+
41+
This strategy is built on two key observations:
42+
43+
1. Each trip contributes a net passenger change at exactly two locations:
44+
- Increase at the pickup location (from)
45+
- Decrease at the drop-off location (to)
46+
47+
2. The car’s capacity must never be exceeded at any point on the journey, so we monitor the cumulative passenger count
48+
as we move forward in time.
49+
50+
This strategy leverages the difference array pattern, which is a version of merge intervals. Rather than merging
51+
overlapping intervals explicitly, it simulates all trips together via a timeline of passenger changes.
52+
53+
Let’s break down the steps:
54+
55+
1. A list timestamp of size 1001 (based on constraints) is created to track changes in passenger counts at each kilometer
56+
point.
57+
2. For each trip `[numPassengersi ,fromi, toi]` in trips:
58+
- Add numPassengers at `timestamp[fromi]`
59+
- Subtract numPassengers at `timestamp[toi]`
60+
61+
This marks the start and end of each passenger interval without iterating over the full range.
62+
63+
3. To simulate the trip and track capacity, initialize a variable used_capacity = 0.
64+
4. Iterate through the timestamp list, adding the passenger changes at each point. If at any point used_capacity > capacity,
65+
return FALSE immediately— the car is overloaded.
66+
5. If the full timeline is processed without exceeding capacity, return TRUE, indicating that all trips can be accommodated.
67+
68+
Let’s look at the following illustration to get a better understanding of the solution:
69+
70+
![Solution 1](./images/solutions/car_pooling_solution_1.png)
71+
![Solution 2](./images/solutions/car_pooling_solution_2.png)
72+
![Solution 3](./images/solutions/car_pooling_solution_3.png)
73+
![Solution 4](./images/solutions/car_pooling_solution_4.png)
74+
![Solution 5](./images/solutions/car_pooling_solution_5.png)
75+
![Solution 6](./images/solutions/car_pooling_solution_6.png)
76+
![Solution 7](./images/solutions/car_pooling_solution_7.png)
77+
![Solution 8](./images/solutions/car_pooling_solution_8.png)
78+
![Solution 9](./images/solutions/car_pooling_solution_9.png)
79+
![Solution 10](./images/solutions/car_pooling_solution_10.png)
80+
![Solution 11](./images/solutions/car_pooling_solution_11.png)
81+
![Solution 12](./images/solutions/car_pooling_solution_12.png)
82+
83+
### Time Complexity
84+
85+
The overall time complexity of the solution is O(n) because:
86+
87+
- The trips list is scanned once to record passenger changes at pickup and drop-off points.
88+
- Each trip results in two constant-time operations: one increment and one decrement in the timeline array.
89+
- The timestamp array (of fixed length 1001) is traversed once to simulate the journey and check capacity constraints.
90+
91+
As the length of timestamp is constant and independent of input size, it contributes O(1) time. So, the total operations
92+
scale linearly with the number of trips.
93+
94+
### Space Complexity
95+
96+
The space complexity of the solution is O(1) because a fixed-size array timestamp of length 1001 is used regardless of
97+
the input size.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
from typing import List, Tuple
2+
3+
4+
def car_pooling(trips: List[List[int]], capacity: int) -> bool:
5+
"""
6+
Calculates and checks whether it is possible to pick up and drop off passengers on the given trips given the car's
7+
capacity
8+
Args:
9+
trips(list): The trips that the car makes while collecting passengers on the route
10+
capacity(int): capacity of the car
11+
Returns:
12+
bool: whether it is possible to collect and drop all passengers along the route
13+
"""
14+
# For every trip, create two entries, the start with the passenger count and end with the passenger count
15+
events: List[Tuple[int, int]] = []
16+
17+
# Create the events
18+
for trip in trips:
19+
num, start, end = trip
20+
# Mark the increase and decrease in passengers at pickup and drop-off points
21+
events.append((start, num)) # pick up
22+
events.append((end, -num)) # drop off
23+
24+
# sort by the location
25+
# If locations are equal, the negative value (drop-off)
26+
# will naturally come before the positive value (pick-up)
27+
events.sort()
28+
29+
# This keeps track of the current vehicle's capacity, which will be used along the trip to check how many passengers
30+
# have been carried so far
31+
current_occupancy = 0
32+
33+
# process events chronologically
34+
for event in events:
35+
location, change = event
36+
current_occupancy += change
37+
if current_occupancy > capacity:
38+
return False
39+
40+
return True
41+
42+
43+
def car_pooling_bucket(trips: List[List[int]], capacity: int) -> bool:
44+
# Initialize a timeline to track changes in passenger count at each km mark (0 to 1000)
45+
timestamp = [0] * 1001
46+
47+
# Mark the increase and decrease in passengers at pickup and drop-off points
48+
for trip in trips:
49+
num_passengers, start, end = trip
50+
timestamp[start] += num_passengers # Pick up passengers
51+
timestamp[end] -= num_passengers # Drop off passengers
52+
53+
# Simulate the car's journey by applying the passenger changes
54+
used_capacity = 0
55+
for passenger_change in timestamp:
56+
used_capacity += passenger_change # Update current passenger count
57+
if used_capacity > capacity: # Check if capacity is exceeded
58+
return False # Trip configuration is invalid
59+
60+
return True # All trips are valid within capacity
115 KB
Loading
85.7 KB
Loading
102 KB
Loading
36.4 KB
Loading
53.7 KB
Loading
46.5 KB
Loading
56 KB
Loading

0 commit comments

Comments
 (0)