LeetCode 2731: Movement of Robots Solution

Master LeetCode problem 2731 (Movement of Robots), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2731. Movement of Robots

Problem Explanation

Explanation:

To solve this problem, we can simulate the movement of robots and calculate the distances between all pairs of robots after each second. We can keep track of the positions of robots in an array and update their positions based on the given movement commands.

  1. Initialize an array to store the positions of robots at indices given by the input array nums.
  2. Iterate through the movement commands string s and for each second:
    • Update the positions of robots based on the movement command.
    • Calculate the distances between all pairs of robots and sum them up.
  3. Return the sum of distances modulo 10^9 + 7.

Time Complexity: O(d * n) where n is the number of robots and d is the number of seconds. Space Complexity: O(n) where n is the number of robots.

:

Solution Code

class Solution {
    public int robotDistance(int[] nums, String s, int d) {
        int n = nums.length;
        long[] positions = new long[n];
        for (int i = 0; i < n; i++) {
            positions[i] = nums[i];
        }
        
        long sumDistances = 0;
        for (int i = 0; i < d; i++) {
            for (int j = 0; j < n; j++) {
                if (s.charAt(j) == 'L') {
                    positions[j]--;
                } else {
                    positions[j]++;
                }
            }
            
            for (int j = 0; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
                    sumDistances += Math.abs(positions[j] - positions[k]);
                }
            }
        }
        
        return (int) (sumDistances % 1000000007);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2731 (Movement of Robots)?

This page provides optimized solutions for LeetCode problem 2731 (Movement of Robots) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2731 (Movement of Robots)?

The time complexity for LeetCode 2731 (Movement of Robots) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2731 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2731 in Java, C++, or Python.

Back to LeetCode Solutions