Minimum Total Distance Traveled solution and explanation
9 more videos on this problem
Minimum Total Distance Traveled | Detailed Thought Process | Leetcode 2463 | codestorywithMIKcodestorywithMIK · 31:58 · 12K views
Minimum Total Distance Traveled | Recursion | DP | Leetcode 2463Techdose · 27:24 · 8K views
leetcode 2463 | Minimum Total Distance Traveled | Leetcode POTD| Dynamic Programming | DSACode With Vick · 26:21 · 812 views
Daily Leetcode #2205: Apr 14, 2026 - 2463. Minimum Total Distance TraveledProgramming Live with Larry · 24:47 · 686 views
2463. Minimum Total Distance Traveled | Leetcode Daily - PythonLeetcode Daily · 3:50 · 546 views
Leetcode 2463. Minimum Total Distance TraveledUnplug Nate · 7:46 · 467 views
Minimum Total Distance Traveled - Leetcode 2463 | Recursive + Memoization | Java | HindiKernel Queen 👑 · 12:22 · 418 views
Leetcode 2463: Minimum Total Distance TraveledAlgorithms Casts · 16:43 · 334 views
Leetcode 2463. Minimum Total Distance Travelled | Daily ChallengeEye on AI and DSA · 27:33 · 235 views
Minimum Total Distance Traveled | LeetCode 2463 - Pythonimpoldev · 16:02 · 158 views
The problem
There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots.
The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially.
All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.
At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots.
Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired.
Note that
- All robots move at the same speed.
- If two robots move in the same direction, they will never collide.
- If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other.
- If a robot passes by a factory that reached its limits, it crosses it as if it does not exist.
- If the robot moved from a position
xto a positiony, the distance it moved is|y - x|.
Example 1:
Input: robot = [0,4,6], factory = [[2,2],[6,2]] Output: 4 Explanation: As shown in the figure: - The first robot at position 0 moves in the positive direction. It will be repaired at the first factory. - The second robot at position 4 moves in the negative direction. It will be repaired at the first factory. - The third robot at position 6 will be repaired at the second factory. It does not need to move. The limit of the first factory is 2, and it fixed 2 robots. The limit of the second factory is 2, and it fixed 1 robot. The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.
Example 2:
Input: robot = [1,-1], factory = [[-2,1],[2,1]] Output: 2 Explanation: As shown in the figure: - The first robot at position 1 moves in the positive direction. It will be repaired at the second factory. - The second robot at position -1 moves in the negative direction. It will be repaired at the first factory. The limit of the first factory is 1, and it fixed 1 robot. The limit of the second factory is 1, and it fixed 1 robot. The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.
Constraints:
1 <= robot.length, factory.length <= 100factory[j].length == 2-109 <= robot[i], positionj <= 1090 <= limitj <= robot.length- The input will be generated such that it is always possible to repair every robot.
Approach overview
Problem Overview: You are given positions of robots and factories on a number line. Each factory can repair a limited number of robots. The goal is to assign every robot to a factory so the total travel distance is minimized while respecting factory capacities.
The key observation: robots and factories lie on a 1D line. After sorting both lists, optimal assignments never cross. A robot to the left will never be assigned to a factory far right if a closer one exists that still has capacity. Sorting simplifies the problem structure and enables dynamic programming.
Approach 1: Greedy Assignment with Capacity Tracking (≈ O((n + m) log m) time, O(m) space)
Start by sorting the robot positions and factories by location using sorting. Process robots from left to right and always try assigning them to the closest factory that still has capacity. A min-heap or ordered structure can track candidate factories and remaining capacity. Each assignment reduces that factory's capacity and contributes abs(robot - factory) to the total distance.
This approach works well when the closest available factory is typically optimal. It relies on the 1D structure of the problem and capacity tracking. However, greedy choices can become tricky when several factories compete for future robots, which is why many interviewers prefer the DP formulation.
Approach 2: Dynamic Programming with Sorted Positions (O(n * m) time, O(n * m) space)
The robust solution models assignments explicitly. First sort robots and factories using array ordering. Let dp[i][j] represent the minimum distance needed to repair the first i robots using the first j factories. For each factory, try repairing k robots (from 0 up to its capacity) and accumulate the distance between those robots and the factory position.
The transition checks all valid k values and updates dp[i][j] from dp[i-k][j-1]. Distances are added incrementally to avoid recomputation. Because robots and factories are sorted, assignments remain ordered and crossing never occurs. This turns a seemingly exponential assignment problem into a structured dynamic programming table.
The DP approach guarantees the optimal assignment and is the most reliable way to handle tight capacity distributions or edge cases where greedy choices fail.
Recommended for interviews: The dynamic programming approach is the expected solution for a hard problem. It demonstrates control over state definition, transitions, and ordered assignments after sorting. Mentioning the greedy intuition first shows you understand the structure, but implementing the DP proves you can reason about optimal substructure and constraints.
Approach 1: Greedy Approach
The Greedy Approach involves sorting both the robots and factories based on their positions. We try to assign each robot to the closest possible factory without exceeding the factory's limit, thus minimizing the travel distance one step at a time.
def min_total_distance(robots, factories):
robots.sort()
factories.sort()
distance = 0
rob_index = 0
fact_index = 0
while rob_index < len(robots):
if factories[fact_index][1] != 0:
distance += abs(robots[rob_index] - factories[fact_index][0])
factories[fact_index][1] -= 1
rob_index += 1
else:
fact_index += 1
return distance
robots = [0, 4, 6]
factories = [[2, 2], [6, 2]]
print("Minimum Total Distance:", min_total_distance(robots, factories))import java.util.Arrays;
class Solution {
public static int minTotalDistance(int[] robots, int[][] factories) {
Arrays.sort(robots);
Arrays.sort(factories, (a, b) -> Integer.compare(a[0], b[0]));
int distance = 0;
int robIndex = 0, factIndex = 0;
while (robIndex < robots.length) {
if (factories[factIndex][1] != 0) {
distance += Math.abs(robots[robIndex] - factories[factIndex][0]);
factories[factIndex][1]--;
robIndex++;
} else {
factIndex++;
}
}
return distance;
}
public static void main(String[] args) {
int[] robots = {0, 4, 6};
int[][] factories = {{2, 2}, {6, 2}};
System.out.println("Minimum Total Distance: " + minTotalDistance(robots, factories));
}
}#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
int minTotalDistance(std::vector<int>& robots, std::vector<std::pair<int, int>>& factories) {
std::sort(robots.begin(), robots.end());
std::sort(factories.begin(), factories.end());
int distance = 0;
size_t robIndex = 0;
size_t factIndex = 0;
while (robIndex < robots.size()) {
if (factories[factIndex].second != 0) {
distance += std::abs(robots[robIndex] - factories[factIndex].first);
factories[factIndex].second--;
robIndex++;
} else {
factIndex++;
}
}
return distance;
}
int main() {
std::vector<int> robots = {0, 4, 6};
std::vector<std::pair<int, int>> factories = {{2, 2}, {6, 2}};
std::cout << "Minimum Total Distance: " << minTotalDistance(robots, factories) << std::endl;
return 0;
}function minTotalDistance(robots, factories) {
robots.sort((a, b) => a - b);
factories.sort((a, b) => a[0] - b[0]);
let distance = 0;
let robIndex = 0;
let factIndex = 0;
while (robIndex < robots.length) {
if (factories[factIndex][1] !== 0) {
distance += Math.abs(robots[robIndex] - factories[factIndex][0]);
factories[factIndex][1]--;
robIndex++;
} else {
factIndex++;
}
}
return distance;
}
const robots = [0, 4, 6];
const factories = [[2, 2], [6, 2]];
console.log("Minimum Total Distance:", minTotalDistance(robots, factories));#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int compare(const void *a, const void *b) {
return (*(int *)a) - (*(int *)b);
}
int minTotalDistance(int* robots, int robotsSize, int** factories, int factoriesSize) {
qsort(robots, robotsSize, sizeof(int), compare);
qsort(factories, factoriesSize, sizeof(factories[0]), compare);
int distance = 0;
int robIndex = 0, factIndex = 0;
while (robIndex < robotsSize) {
if (factories[factIndex][1] != 0) {
distance += abs(robots[robIndex] - factories[factIndex][0]);
factories[factIndex][1]--;
robIndex++;
} else {
factIndex++;
}
}
return distance;
}
int main() {
int robots[] = {0, 4, 6};
int factories[][2] = {{2, 2}, {6, 2}};
int* factoriesPtr[] = {factories[0], factories[1]};
int result = minTotalDistance(robots, 3, factoriesPtr, 2);
printf("Minimum Total Distance: %d\n", result);
return 0;
}using System;
using System.Linq;
class Solution {
public static int MinTotalDistance(int[] robots, int[][] factories) {
Array.Sort(robots);
Array.Sort(factories, (a, b) => a[0].CompareTo(b[0]));
int distance = 0;
int robIndex = 0, factIndex = 0;
while (robIndex < robots.Length) {
if (factories[factIndex][1] != 0) {
distance += Math.Abs(robots[robIndex] - factories[factIndex][0]);
factories[factIndex][1]--;
robIndex++;
} else {
factIndex++;
}
}
return distance;
}
public static void Main(string[] args) {
int[] robots = {0, 4, 6};
int[][] factories = {new int[] {2, 2}, new int[] {6, 2}};
Console.WriteLine("Minimum Total Distance: " + MinTotalDistance(robots, factories));
}
}The Python solution employs sorting for both robots and factories, followed by assigning robots to the nearest available factories under their limit constraints.
Time Complexity: O(n log n + m log m), for sorting. The rest is linear.
Space Complexity: O(1), except the input space.
Approach 2: Dynamic Programming Approach
A Dynamic Programming approach could involve maintaining a DP table where each entry dp[i][j] represents the minimum distance needed to repair the first i robots using the first j factories. This approach could find optimal assignments by considering various combinations and memoizing the results, though it might be more computationally intensive for larger datasets than the greedy approach.
def min_total_distance_dp(robots, factories):
robots.sort()
factories.sort()
n = len(robots)
m = len(factories)
# DP Table Initialization
INF = float('inf')
dp = [[INF] * (m+1) for _ in range(n+1)]
dp[0][0] = 0
for i in range(1, n+1):
for j in range(1, m+1):
dp[i][j] = dp[i][j-1] # Ignore current factory
if factories[j-1][1] > 0:
cumulative_distance = 0
# Assign robots to this factory
for k in range(1, min(factories[j-1][1], i)+1):
cumulative_distance += abs(robots[i-k] - factories[j-1][0])
dp[i][j] = min(dp[i][j], dp[i-k][j-1] + cumulative_distance)
return dp[n][m]
robots = [0, 4, 6]
factories = [[2, 2], [6, 2]]
print("Minimum Total Distance (DP):", min_total_distance_dp(robots, factories))In this Python solution, a DP table is constructed that tracks the minimum distance for repairing a certain number of robots using a given number of factories. By incrementally building up solutions for subproblems, it finds the optimal total travel distance.
Time Complexity: O(n * m * l), where l is the maximum capacity of a factory, due to nested loops.
Space Complexity: O(n * m), for storing the DP table.
Approach 3: Memoization Search
First, we sort the robots and factories in ascending order. Then we define a function dfs(i, j) to represent the minimum total moving distance starting from the i-th robot and the j-th factory.
For dfs(i, j), if the j-th factory does not repair the robot, then dfs(i, j) = dfs(i, j+1). If the j-th factory repairs the robot, we can enumerate the number of robots repaired by the j-th factory and find the minimum total moving distance. That is, dfs(i, j) = min(dfs(i + k + 1, j + 1) + sum_{t = 0}^{k} |robot[i + t] - factory[j][0]|).
The time complexity is O(m^2 times n), and the space complexity is O(m times n). Here, m and n are the number of robots and factories, respectively.
func minimumTotalDistance(robot []int, factory [][]int) int64 {
sort.Ints(robot)
sort.Slice(factory, func(i, j int) bool { return factory[i][0] < factory[j][0] })
f := make([][]int, len(robot))
for i := range f {
f[i] = make([]int, len(factory))
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if i == len(robot) {
return 0
}
if j == len(factory) {
return 1e15
}
if f[i][j] != 0 {
return f[i][j]
}
ans := dfs(i, j+1)
t := 0
for k := 0; k < factory[j][1]; k++ {
if i+k >= len(robot) {
break
}
t += abs(robot[i+k] - factory[j][0])
ans = min(ans, t+dfs(i+k+1, j+1))
}
f[i][j] = ans
return ans
}
return int64(dfs(0, 0))
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}Complexity comparison
| Approach | Complexity |
|---|---|
| Greedy Approach | Time Complexity: O(n log n + m log m), for sorting. The rest is linear. |
| Dynamic Programming Approach | Time Complexity: O(n * m * l), where l is the maximum capacity of a factory, due to nested loops. |
| Memoization Search | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy with Capacity Tracking | O((n + m) log m) | O(m) | When factories are processed dynamically and nearest assignment usually works |
| Dynamic Programming on Sorted Robots and Factories | O(n * m) | O(n * m) | General optimal solution when capacities and positions create complex assignment choices |
Frequently asked questions
Is Minimum Total Distance Traveled easy or hard?
Minimum Total Distance Traveled is classified as a Hard problem on LeetCode. The difficulty comes from combining sorting, capacity constraints, and dynamic programming state transitions to compute the optimal assignment.
Minimum Total Distance Traveled Python/Java solution
Python implementations usually use a DP table or memoized recursion after sorting robots and factories. Java solutions follow the same logic with iterative DP and nested loops over robots and factories. Both implementations achieve O(n * m) time complexity.
How to solve Minimum Total Distance Traveled in O(n*m)?
Sort robots and factories by position first. Define dp[i][j] as the minimum distance to repair the first i robots using the first j factories. For each factory, try assigning up to its capacity robots and update dp using dp[i-k][j-1] plus the accumulated distance to that factory.
What is the best approach for Minimum Total Distance Traveled?
Dynamic programming after sorting robots and factories is the most reliable solution. The DP state tracks the minimum distance to repair the first i robots using the first j factories while respecting factory capacities. This guarantees an optimal assignment and typically runs in O(n * m) time.
Is Minimum Total Distance Traveled asked at Google/Amazon/Meta?
Problems involving robot-factory assignment, capacity constraints, and dynamic programming appear in interviews at companies like Google, Amazon, and Meta. Variations of this problem test sorting combined with DP state transitions and optimal assignment reasoning.
What data structure is used in Minimum Total Distance Traveled?
Arrays store robot and factory positions, and sorting is applied to maintain ordered assignments. The optimal solution primarily relies on dynamic programming tables. Some alternative implementations also use heaps or priority queues to support greedy assignment strategies.
What is the time complexity of Minimum Total Distance Traveled?
The standard dynamic programming solution runs in O(n * m) time where n is the number of robots and m is the number of factories. Space complexity is also O(n * m) for the DP table. Greedy-style implementations with heaps can approach O((n + m) log m) but may not cover all edge cases as reliably as DP.
