LeetCode 2142: The Number of Passengers in Each Bus I Solution

Master LeetCode problem 2142 (The Number of Passengers in Each Bus I), 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.

2142. The Number of Passengers in Each Bus I

Medium

Problem Explanation

Explanation:

To solve this problem, we can iterate over the events and keep track of the number of passengers on each bus at any given time. We can use a hashmap to store the number of passengers on each bus. We will update the passenger count based on the events received.

  1. Initialize an empty hashmap to store the number of passengers on each bus.
  2. Iterate over the events and update the passenger count for each bus based on the event type.
  3. Return the list of passenger counts for each bus.

Time complexity: O(n), where n is the number of events Space complexity: O(n), where n is the number of buses

:

Solution Code

class Solution {
    public List<Integer> countPassengers(int[][] events) {
        Map<Integer, Integer> passengers = new HashMap<>();
        List<Integer> result = new ArrayList<>();
        
        for (int[] event : events) {
            int busId = event[1];
            int passengersOnBus = passengers.getOrDefault(busId, 0);
            
            if (event[0] == 0) {
                passengersOnBus += event[2];
            } else {
                passengersOnBus -= event[2];
            }
            
            passengers.put(busId, passengersOnBus);
        }
        
        for (int busId : passengers.keySet()) {
            result.add(passengers.get(busId));
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2142 (The Number of Passengers in Each Bus I)?

This page provides optimized solutions for LeetCode problem 2142 (The Number of Passengers in Each Bus I) 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 2142 (The Number of Passengers in Each Bus I)?

The time complexity for LeetCode 2142 (The Number of Passengers in Each Bus I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2142 on DevExCode?

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

Back to LeetCode Solutions