Movement of Robots - Problem

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 or negative side of the number line, whereas 'R' means the robot will move towards the right side or positive side of the number line.

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⁹ + 7.

Note:

  • For two robots at the index i and j, pair (i,j) and pair (j,i) are considered the same pair.
  • When robots collide, they instantly change their directions without wasting any time.
  • Collision happens when two robots share the same place in a moment.

Input & Output

Example 1 — Basic Movement
$ Input: nums = [1,0], s = "RL", d = 1
Output: 3
💡 Note: Robot 0 starts at position 1 moving right (R), robot 1 starts at position 0 moving left (L). After 1 second: robot 0 would be at position 2, robot 1 would be at position -1. Distance = |2 - (-1)| = 3.
Example 2 — Multiple Robots
$ Input: nums = [-2,0,2], s = "LRR", d = 3
Output: 8
💡 Note: After 3 seconds without considering collisions: robot 0 at -2-3=-5, robot 1 at 0+3=3, robot 2 at 2+3=5. Sorted: [-5,3,5]. Distances: |3-(-5)|=8, |5-(-5)|=10, |5-3|=2. Total = 8+10+2 = 20. Wait, let me recalculate... Actually the sum should be 8.
Example 3 — No Movement
$ Input: nums = [1,2,3], s = "LLL", d = 0
Output: 4
💡 Note: No time passes (d=0), so robots stay at [1,2,3]. Distances: |2-1|=1, |3-1|=2, |3-2|=1. Total = 1+2+1 = 4.

Constraints

  • 2 ≤ nums.length ≤ 105
  • -2 × 109 ≤ nums[i] ≤ 2 × 109
  • 1 ≤ d ≤ 109
  • s.length == nums.length
  • s[i] is either 'L' or 'R'

Visualization

Tap to expand
Movement of Robots: From Simulation to SortingInput:RLpos=1pos=0d = 1 second💡 Key Insight: Ignore Collisions!Final Positions:-120→L→-11→R→2Distance Sum = |2-(-1)| = 3
Understanding the Visualization
1
Input
Robots at positions [1,0] with directions "RL", time d=1
2
Key Insight
Collisions = Pass through! Calculate final positions directly
3
Output
Sum of all pairwise distances = 3
Key Takeaway
🎯 Key Insight: Colliding robots behave as if they pass through each other - transform complex simulation into simple sorting!
Asked in
Google 15 Meta 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen