#2731

Movement of Robots

Medium
ArrayBrainteaserSortingPrefix SumSortingPrefix Sum
LeetCode ↗

Approaches

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

Intuition

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

In the optimal solution, we can ignore the collisions and directly calculate the final positions of the robots after 'd' seconds. By sorting these positions, we can efficiently compute the sum of distances using a prefix sum approach.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the final position of each robot after 'd' seconds based on its direction.
  2. 2Step 2: Sort the final positions.
  3. 3Step 3: Use a prefix sum to calculate the total distance efficiently.
solution.py14 lines
1# Full working Python code
2
3def sum_of_distances(nums, s, d):
4    n = len(nums)
5    positions = [0] * n
6    for i in range(n):
7        positions[i] = nums[i] + d if s[i] == 'R' else nums[i] - d
8    positions.sort()
9    total_distance = 0
10    prefix_sum = 0
11    for i in range(n):
12        total_distance += positions[i] * i - prefix_sum
13        prefix_sum += positions[i]
14    return total_distance % (10**9 + 7)

Complexity note: The time complexity is O(n log n) due to the sorting step. The space complexity is O(n) for storing the positions of the robots.

  • 1Ignoring collisions simplifies the problem.
  • 2Sorting helps in efficiently calculating distances.

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