Leetcode 2731: Movement of Robots

grid47
grid47
Exploring patterns and algorithms
Feb 7, 2024 6 min read

A number of robots are standing on an infinite number line with their initial positions given in the array nums. Each robot will move based on a command string s where ‘L’ means left and ‘R’ means right. If two robots collide, they instantly reverse their directions. Your task is to calculate the sum of the distances between all pairs of robots d seconds after the command.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array `nums` representing the initial positions of robots, a string `s` representing the movement directions, and an integer `d` representing the number of seconds after the command.
Example: `nums = [2, 5, 8]`, `s = 'LLR'`, `d = 2`
Constraints:
• 2 <= nums.length <= 10^5
• -2 * 10^9 <= nums[i] <= 2 * 10^9
• 0 <= d <= 10^9
• nums.length == s.length
• s consists of 'L' and 'R' only
• nums[i] are unique
Output: Return the sum of distances between all pairs of robots after `d` seconds. The result should be returned modulo 10^9 + 7.
Example: For `nums = [2, 5, 8]`, `s = 'LLR'`, and `d = 2`, the output is `24`.
Constraints:
• The result should be returned modulo 10^9 + 7.
Goal: Calculate the sum of distances between all pairs of robots after moving for `d` seconds.
Steps:
• For each robot, adjust its position based on its movement direction and the time `d`.
• Sort the final positions of the robots.
• For each pair of robots, calculate the absolute distance between them.
• Sum the distances and return the result modulo 10^9 + 7.
Goal: The constraints define the number of robots and the time `d` within manageable limits.
Steps:
• 2 <= nums.length <= 10^5
• nums[i] are unique
• -2 * 10^9 <= nums[i] <= 2 * 10^9
• 0 <= d <= 10^9
Assumptions:
• The input is always valid with no duplicates in the positions.
• The robots move in exactly one direction as specified by the string `s`.
Input: Example 1
Explanation: For `nums = [2, 5, 8]`, `s = 'LLR'`, and `d = 2`, the positions of the robots will be updated each second and we compute the sum of the distances after `d` seconds.

Input: Example 2
Explanation: For `nums = [1, 0]`, `s = 'RL'`, and `d = 1`, after one second, the robots are at positions `[2, -1]` and we calculate the distance between them.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus