LeetCode 2238: Number of Times a Driver Was a Passenger Solution

Master LeetCode problem 2238 (Number of Times a Driver Was a Passenger), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2238. Number of Times a Driver Was a Passenger

Medium

Problem Explanation

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.

  1. Initialize a hashmap to store the count of each driver as a passenger.
  2. Iterate through the list of trips:
    • For each trip, update the count of the driver and passenger.
  3. 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.

Solution Code

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);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2238 (Number of Times a Driver Was a Passenger)?

This page provides optimized solutions for LeetCode problem 2238 (Number of Times a Driver Was a Passenger) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2238 (Number of Times a Driver Was a Passenger)?

The time complexity for LeetCode 2238 (Number of Times a Driver Was a Passenger) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2238 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2238 in Java, C++, or Python.

Back to LeetCode Solutions