LeetCode 2238: Number of Times a Driver Was a Passenger
Problem Description
Explanation
To solve this problem, we can iterate through the list of trips and maintain a map to keep track of the number of times each driver was a passenger. For each trip, we update the count for the driver and the passenger accordingly. Finally, we return the count for the given driver.
- Initialize a hashmap to store the count of each driver as a passenger.
- Iterate through the list of trips:
- For each trip, update the count of the driver and passenger.
- Return the count for the given driver.
Time Complexity
The time complexity of this solution is O(N) where N is the number of trips.
Space Complexity
The space complexity of this solution is O(N) to store the count of each driver.
Solutions
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public int numOfTimesDriverWasPassenger(int driver, List<List<Integer>> trips) {
Map<Integer, Integer> passengerCount = new HashMap<>();
for (List<Integer> trip : trips) {
int driverTrip = trip.get(0);
int passengerTrip = trip.get(1);
passengerCount.put(driverTrip, passengerCount.getOrDefault(driverTrip, 0) + 1);
passengerCount.put(passengerTrip, passengerCount.getOrDefault(passengerTrip, 0) - 1);
}
return passengerCount.getOrDefault(driver, 0);
}
}
Loading editor...