#2731
Medium Algorithms Movement of robots
Array Brainteaser Sorting Prefix Sum
27.9% acceptance
Feb 25, 2026
542
103
Some robots are standing on an infinite number line with their initial coordinates given by a 0-indexed integer array nums and will start moving once given the command to move. The robots will move a unit distance each second.
You are given a string s denoting the direction in which robots will move on command. 'L' means the robot will move towards the left side, whereas 'R' means the robot will move towards the right side.
If two robots collide, they will start moving in opposite directions.
Return the sum of distances between all the pairs of robots d seconds after the command. Since the sum can be very large, return it modulo 10^9 + 7.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn sum_distance(nums: Vec<i32>, s: String, d: i32) -> i32 {
const MOD: i64 = 1_000_000_007;
let mut pos: Vec<i64> = nums
.iter()
.zip(s.bytes())
.map(|(&n, dir)| {
if dir == b'R' { n as i64 + d as i64 } else { n as i64 - d as i64 }
})
.collect();
pos.sort();
let mut prefix = 0i64;
let mut ans = 0i64;
for (i, &p) in pos.iter().enumerate() {
ans = (ans + p * i as i64 - prefix) % MOD;
prefix += p;
}
((ans % MOD + MOD) % MOD) as i32
}
}