The Movement of Robots problem places robots on a number line, each moving either left or right. When two robots collide, they both reverse direction. Find the sum of absolute distances between all pairs of robots after d seconds. This Movement of Robots coding problem uses the classic "robots pass through each other" observation combined with prefix sums for efficient pair-distance computation.
Meta and Google ask this medium problem because it requires the non-obvious insight that colliding robots are equivalent to robots passing through each other — only the relative order of positions changes. After this observation, compute final positions, sort them, and use prefix sums to compute all pairwise distances efficiently. The brainteaser, array, sorting, and prefix sum interview pattern is showcased.
Position-passing observation + prefix sum pair distances. When robots collide and reverse, it's equivalent to them passing through each other (only their "labels" switch). So compute each robot's final position directly: pos + d (if moving right) or pos - d (if moving left). Sort final positions. The sum of all pairwise absolute distances: sum_{i<j} |pos[i] - pos[j]| = for each j, contribute pos[j] * j - prefixSum[j]. Compute using prefix sums.
Robots: [-2, 0, 2], directions: [right, left, left]. d=3.
The "robots reverse = robots pass through" insight is a classic brainteaser that reduces a complex simulation to a simple formula. After learning this, practice the prefix sum formula for sum of all pairwise distances in a sorted array: sum_{j} (pos[j] * j - prefixSum[j]). This formula appears in many geometry and sorting problems. Recognizing the brainteaser observation is the hard part; the prefix sum computation is standard. Practice both independently.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Describe the Painting | Medium | Solve | |
| Average Height of Buildings in Each Segment | Medium | Solve | |
| Brightest Position on Street | Medium | Solve | |
| Find Polygon With the Largest Perimeter | Medium | Solve | |
| Maximum Sum Obtained of Any Permutation | Medium | Solve |