Simulate 1-D collisions and scale to huge inputs
Company: SoFi
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: HR Screen
Quick Answer: This question evaluates a candidate's algorithm design skills, proficiency with appropriate data structures, and ability to analyze time and space complexity alongside system-level scalability concerns for large datasets.
Constraints
- 2 <= asteroids.length (the surrounding problem assumes at least a few elements, but the solution also handles 0 and 1)
- -1000 <= asteroids[i] <= 1000
- asteroids[i] != 0 (every object has a direction and nonzero mass)
Examples
Input: ([5, 10, -5],)
Expected Output: [5, 10]
Explanation: The -5 meets the 10 (larger) and is destroyed; 5 and 10 survive since they never meet.
Input: ([8, -8],)
Expected Output: []
Explanation: Equal masses moving toward each other destroy both.
Input: ([10, 2, -5],)
Expected Output: [10]
Explanation: -5 destroys 2 (smaller), then meets 10 (larger) and is destroyed; only 10 remains.
Input: ([-2, -1, 1, 2],)
Expected Output: [-2, -1, 1, 2]
Explanation: All left-movers precede all right-movers, so nothing ever collides.
Input: ([1, -2, -2, -2],)
Expected Output: [-2, -2, -2]
Explanation: The first -2 destroys the 1, then the remaining left-movers pass freely.
Input: ([],)
Expected Output: []
Explanation: Empty input yields an empty result.
Input: ([7],)
Expected Output: [7]
Explanation: A single object never collides.
Input: ([-3, 3],)
Expected Output: [-3, 3]
Explanation: A left-mover followed by a right-mover diverge and never meet.
Input: ([3, -3, 3, -3],)
Expected Output: []
Explanation: Each adjacent right/left equal-mass pair annihilates, leaving nothing.
Input: ([5, -5, -6, 6],)
Expected Output: [-6, 6]
Explanation: 5 and -5 annihilate; then -6 has nothing to its left to hit, and 6 diverges from it, so -6 and 6 survive.
Hints
- A collision can only happen between a right-moving object (positive) and a left-moving object (negative) that appears immediately after it. Same-direction or diverging neighbors never meet.
- Use a stack of the surviving objects so far. The only object the current one can collide with is the top of the stack.
- When the current object moves left (negative), repeatedly compare it against positive objects on top of the stack: pop the smaller, pop both on a tie, and stop (current destroyed) if the top is larger or equal.