19. Bus Conductor

βœ… GFG solution to the Bus Conductor problem: find minimum moves to assign passengers to chairs using greedy sorting approach. πŸš€

The problem can be found at the following link: πŸ”— Question Link

🧩 Problem Description

You are a conductor of a bus. You are given two arrays chairs[] and passengers[] of equal length, where chairs[i] is the position of the ith chair and passengers[j] is the position of the jth passenger. You may perform the following move any number of times:

  • Increase or decrease the position of the ith passenger by 1 (i.e., moving the ith passenger from position x to x+1 or x-1)

Return the minimum number of moves required to move each passenger to get a chair.

Note: Although multiple chairs can occupy the same position, each passenger must be assigned to exactly one unique chair.

πŸ“˜ Examples

Example 1

Input: chairs[] = [3, 1, 5], passengers[] = [2, 7, 4]
Output: 4
Explanation: The passengers are moved as follows:
- The first passenger is moved from position 2 to position 1 using 1 move.
- The second passenger is moved from position 7 to position 5 using 2 moves.
- The third passenger is moved from position 4 to position 3 using 1 move.
In total, 1 + 2 + 1 = 4 moves were used.

Example 2

πŸ”’ Constraints

  • $1 \le n \le 10^5$

  • $1 \le \text{chairs}[i], \text{passengers}[j] \le 10^4$

βœ… My Approach

The optimal solution uses a Greedy Sorting strategy to minimize total moves:

Greedy Sorting Strategy

  1. Key Insight:

    • To minimize total distance, we should pair the smallest chair position with the smallest passenger position, second smallest with second smallest, and so on.

    • This greedy approach ensures optimal assignment without considering all possible permutations.

  2. Sort Both Arrays:

    • Sort chairs[] in ascending order to arrange chair positions from smallest to largest.

    • Sort passengers[] in ascending order to arrange passenger positions from smallest to largest.

  3. Calculate Minimum Moves:

    • After sorting, iterate through both arrays simultaneously.

    • For each index i, calculate the absolute difference: |chairs[i] - passengers[i]|.

    • This difference represents the minimum moves needed to move passenger i to chair i.

  4. Accumulate Total:

    • Sum all individual move distances to get the total minimum moves required.

  5. Why This Works:

    • Sorting ensures we're making locally optimal choices at each step.

    • Pairing nearest positions minimizes crossing paths and redundant movements.

    • The greedy choice property guarantees global optimality for this problem.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n log n), as we perform sorting on both arrays which dominates the complexity. The subsequent linear traversal to calculate moves takes O(n), but sorting is the bottleneck.

  • Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables (res, n, i). The sorting is typically done in-place or with O(log n) stack space for recursion, which is considered constant for practical purposes.

πŸ§‘β€πŸ’» Code (C++)

⚑ View Alternative Approaches with Code and Analysis

πŸ“Š 2️⃣ Priority Queue Approach

πŸ’‘ Algorithm Steps:

  1. Insert all chair positions into a min-heap.

  2. Insert all passenger positions into another min-heap.

  3. Pop smallest elements from both heaps simultaneously.

  4. Calculate absolute difference and accumulate moves.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n) - Heap construction and operations

  • Auxiliary Space: πŸ’Ύ O(n) - Two heaps storing all elements

βœ… Why This Approach?

  • Natural ordering through heap structure

  • Flexible for streaming data scenarios

  • Good for practicing heap operations

πŸ“Š 3️⃣ Index-Based Direct Mapping

πŸ’‘ Algorithm Steps:

  1. Sort both arrays to establish optimal pairing.

  2. Use transform function with iterators for functional style.

  3. Accumulate differences using standard library algorithms.

  4. Return total accumulated moves.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n) - Dominated by sorting

  • Auxiliary Space: πŸ’Ύ O(1) - No extra data structures

βœ… Why This Approach?

  • Modern C++ functional programming style

  • Compact and expressive code

  • Efficient single-pass accumulation

πŸ“Š 4️⃣ Two Pointer Technique

πŸ’‘ Algorithm Steps:

  1. Sort both arrays independently.

  2. Use two pointers starting from beginning of each array.

  3. Calculate distance for each matched pair.

  4. Move both pointers forward synchronously.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n) - Sorting dominates

  • Auxiliary Space: πŸ’Ύ O(1) - Only pointer variables

βœ… Why This Approach?

  • Clear two-pointer pattern demonstration

  • Easy to trace and debug

  • Extensible for constraint variations

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ Greedy Sorting

🟒 O(n log n)

🟒 O(1)

πŸš€ Optimal space usage

πŸ”§ Requires sorting

πŸ” Priority Queue

🟒 O(n log n)

🟑 O(n)

πŸ“– Natural ordering

πŸ’Ύ Extra heap space

πŸ“Š Functional STL

🟒 O(n log n)

🟒 O(1)

🎯 Modern C++ style

🧩 Lambda complexity

πŸ”„ Two Pointer

🟒 O(n log n)

🟒 O(1)

⭐ Classic pattern

πŸ”§ Similar to greedy

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Greedy Sorting

β˜…β˜…β˜…β˜…β˜…

πŸ“– Learning heap structures

πŸ₯ˆ Priority Queue

β˜…β˜…β˜…β˜…β˜†

πŸ”§ Modern C++ interview

πŸ₯‰ Functional STL

β˜…β˜…β˜…β˜…β˜†

🎯 Two-pointer practice

πŸ… Two Pointer

β˜…β˜…β˜…β˜…β˜…

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated