714171. Bus Conductor

Easy

Bus Conductor

Slug: bus-conductor--170647 Difficulty: Easy Id: 714171 Topic Tags: Arrays, Sorting Company Tags: None

Summary

The Bus Conductor problem involves arranging a set of buses in a specific order based on their arrival times and departure times. The key concepts involved are arrays and sorting.

Detailed Explanation

Given an array of bus arrival and departure times, find the sequence of buses that should be arranged at each stop in such a way that no two buses arrive or depart simultaneously. This problem is equivalent to finding the maximum number of buses that can be served at a stop without any collision.

To solve this problem, we first sort the bus arrival and departure times in ascending order. Then, iterate through the sorted array, keeping track of the current bus being served (if any) and the next available time slot. If the current bus is departing or there's no bus being served, update the current bus to the one arriving at the next available time slot.

Here's a step-by-step breakdown:

  1. Sort the bus arrival and departure times in ascending order.
  2. Initialize variables: current_bus, next_available_time, and max_buses_served.
  3. Iterate through the sorted array:
    • If the current bus is departing or there's no bus being served, update current_bus to the one arriving at next_available_time.
    • Update next_available_time to the departure time of the current bus.
  4. Return the sequence of buses that should be arranged at each stop.

Time complexity: O(n log n) due to sorting Space complexity: O(1) as we only use a constant amount of space

Optimized Solutions

Java

View on GeeksforGeeks
public class BusConductor {
    public static String[] busConductor(int[][] buses) {
        Arrays.sort(buses, (a, b) -> a[0] - b[0]);
        int currentBus = 0;
        int nextAvailableTime = buses[0][0];
        List<String> result = new ArrayList<>();
        for (int i = 0; i < buses.length; i++) {
            if (currentBus == buses[i].length - 1 || buses[i][1] > nextAvailableTime) {
                currentBus = 0;
                nextAvailableTime = buses[i][0];
            }
            result.add("Bus " + (i + 1));
        }
        return result.toArray(new String[0]);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.