Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Car Pooling in Python
Car pooling is a common algorithmic problem where we need to determine if a vehicle can accommodate all passenger trips without exceeding its capacity. The vehicle travels only eastward, picking up and dropping off passengers at specific locations.
Problem Understanding
Given a list of trips where each trip contains [num_passengers, start_location, end_location] and a vehicle capacity, we need to check if all trips can be completed without exceeding the capacity limit.
Algorithm Approach
We use a difference array technique to track passenger changes at each location ?
- Create an array to track passenger count changes at each location
- For each trip, increment passengers at start location and decrement at end location
- Simulate the journey, checking if capacity is ever exceeded
Implementation
class Solution:
def carPooling(self, trips, capacity):
stops = [0 for i in range(1001)]
# Mark passenger changes at each location
for trip in trips:
num_passengers, start, end = trip
stops[start] += num_passengers
stops[end] -= num_passengers
# Simulate the journey
current_passengers = 0
for passengers_change in stops:
current_passengers += passengers_change
if current_passengers > capacity:
return False
return True
# Test the solution
solution = Solution()
trips = [[2,1,5],[3,3,7]]
capacity = 5
result = solution.carPooling(trips, capacity)
print(f"Can complete all trips: {result}")
Can complete all trips: True
Step-by-Step Execution
Let's trace through the example with trips [[2,1,5],[3,3,7]] and capacity 5 ?
def carPooling_detailed(trips, capacity):
stops = [0] * 1001
print("Processing trips:")
for trip in trips:
passengers, start, end = trip
stops[start] += passengers
stops[end] -= passengers
print(f"Trip {trip}: +{passengers} at location {start}, -{passengers} at location {end}")
print("\nSimulating journey:")
current_passengers = 0
for location, change in enumerate(stops[:10]): # Show first 10 locations
if change != 0:
current_passengers += change
print(f"Location {location}: {change:+d} passengers, total: {current_passengers}")
if current_passengers > capacity:
print(f"Capacity exceeded! ({current_passengers} > {capacity})")
return False
return True
# Test with detailed output
trips = [[2,1,5],[3,3,7]]
capacity = 5
result = carPooling_detailed(trips, capacity)
print(f"\nFinal result: {result}")
Processing trips: Trip [2, 1, 5]: +2 passengers at location 1, -2 passengers at location 5 Trip [3, 3, 7]: +3 passengers at location 3, -3 passengers at location 7 Simulating journey: Location 1: +2 passengers, total: 2 Location 3: +3 passengers, total: 5 Location 5: -2 passengers, total: 3 Location 7: -3 passengers, total: 0 Final result: True
Edge Cases
Let's test a case where capacity is exceeded ?
# Test case where capacity is exceeded
solution = Solution()
# More passengers than capacity
trips_fail = [[2,1,5],[4,1,3]]
capacity_fail = 4
result_fail = solution.carPooling(trips_fail, capacity_fail)
print(f"Overlapping trips exceeding capacity: {result_fail}")
# Single trip within capacity
trips_pass = [[3,2,8]]
capacity_pass = 5
result_pass = solution.carPooling(trips_pass, capacity_pass)
print(f"Single trip within capacity: {result_pass}")
Overlapping trips exceeding capacity: False Single trip within capacity: True
Time and Space Complexity
- Time Complexity: O(n + k) where n is the number of trips and k is the maximum location (1000)
- Space Complexity: O(k) for the stops array
Conclusion
The car pooling algorithm efficiently uses a difference array to track passenger changes at each location. By simulating the journey and checking capacity at each stop, we can determine if all trips are feasible within the given constraints.
