#2463

Minimum Total Distance Traveled

Hard
ArrayDynamic ProgrammingSortingGreedy AlgorithmsSortingTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution sorts both robots and factories, then uses a greedy approach to assign robots to the nearest available factory. This minimizes the distance efficiently by ensuring that each factory repairs as many robots as possible within its limit.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the robot and factory arrays based on their positions.
  2. 2Step 2: Use two pointers to traverse the robots and factories.
  3. 3Step 3: For each robot, assign it to the nearest factory that has not reached its limit, updating the total distance accordingly.
solution.py12 lines
1def minDistance(robot, factory):
2    robot.sort()
3    factory.sort()
4    total_distance = 0
5    j = 0
6    for r in robot:
7        while j < len(factory) and factory[j][1] == 0:
8            j += 1
9        if j < len(factory):
10            total_distance += abs(r - factory[j][0])
11            factory[j][1] -= 1
12    return total_distance

Complexity note: The sorting step dominates the complexity, making it O(n log n), while the traversal of robots and factories is linear.

  • 1Sorting both robots and factories allows for efficient pairing based on proximity.
  • 2Using a greedy approach ensures that we minimize the distance for each robot by always choosing the nearest available factory.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.