← JP Morgan Interview Insights

JP Morgan·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
May 2026

Summary

JP Morgan software engineer round with a stack-based simulation problem. Nothing too brutal but you'd better know your asteroid collision variants cold before walking in.

Questions Asked (1)

Q1

Given an array of integers representing asteroids moving in a row, simulate their collisions and return the final state. Each asteroid's absolute value is its size and the sign indicates direction. Smaller asteroids explode on collision; equal sizes both explode; same-direction asteroids never collide.

Algorithms & Data Structures
Author's notes

Basically a stack problem once you see it.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Use a stack to simulate collisions by iterating through the array and processing each asteroid against the top of the stack. Only right-moving asteroids followed by left-moving ones can collide, so handle cases based on direction and size, popping from the stack as needed. Finally, the stack contains the surviving asteroids in order.

Pro tip: Clarify edge cases upfront, such as empty input or all asteroids moving in the same direction, and mention that the stack approach runs in O(n) time and O(n) space, which is optimal.

1. Understand the problem

Restate the collision rules: asteroids move in their sign direction, collisions only occur when a right-moving asteroid meets a left-moving one, and the smaller one explodes (both if equal).

2. Choose data structure

Select a stack to efficiently simulate collisions, as it allows easy access to the most recent asteroid that could collide with the current one.

3. Iterate and simulate

For each asteroid, while the stack is not empty, the top is positive (moving right), and the current is negative (moving left), resolve the collision by comparing absolute values and popping or breaking accordingly.

4. Handle survivors

After processing collisions, if the current asteroid survives (either it destroyed the top or no collision occurred), push it onto the stack.

5. Return result

Convert the stack to an array and return it as the final state of the asteroids.

Key Points to Mention

  • Use a stack to simulate collisions in O(n) time.
  • Collisions only happen when a right-moving asteroid is followed by a left-moving one.
  • Compare absolute values to determine which asteroid survives.
  • Equal sizes result in both asteroids exploding.
  • Same-direction asteroids never collide, so they are simply pushed onto the stack.
  • Edge cases: empty array, all asteroids moving same direction, and multiple collisions in a row.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.