LeetCode 2751: Robot Collisions Solution
Master LeetCode problem 2751 (Robot Collisions), a hard 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.
2751. Robot Collisions
Problem Explanation
Explanation:
To solve this problem, we can simulate the movements of the robots and handle collisions as described. We can use a priority queue to keep track of the robots in the order of their positions.
- Initialize a priority queue to store the robots based on their positions.
- Iterate through the robots in the order of their indices.
- For each robot:
- Calculate its next position based on its direction.
- Check for collisions with other robots in the priority queue.
- Resolve collisions based on health values.
- Update the health of surviving robots.
- Return the health values of the surviving robots in the order they were given in the input.
Time complexity: O(n log n) where n is the number of robots. Space complexity: O(n) for the priority queue.
:
Solution Code
import java.util.*;
class Solution {
public int[] robotCollisions(int[] positions, int[] healths, String directions) {
int n = positions.length;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
for (int i = 0; i < n; i++) {
pq.offer(new int[]{positions[i], healths[i], i});
}
while (!pq.isEmpty()) {
int[] current = pq.poll();
int nextPos = current[0] + (directions.charAt(current[2]) == 'R' ? 1 : -1);
if (!pq.isEmpty() && nextPos == pq.peek()[0]) {
int[] next = pq.poll();
if (current[1] > next[1]) {
pq.offer(new int[]{nextPos, current[1] - next[1], current[2]});
} else if (current[1] < next[1]) {
pq.offer(new int[]{next[0], next[1] - current[1], next[2]});
}
}
}
List<Integer> result = new ArrayList<>();
for (int[] robot : pq) {
result.add(robot[1]);
}
return result.stream().mapToInt(i -> i).toArray();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2751 (Robot Collisions)?
This page provides optimized solutions for LeetCode problem 2751 (Robot Collisions) 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 2751 (Robot Collisions)?
The time complexity for LeetCode 2751 (Robot Collisions) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2751 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2751 in Java, C++, or Python.