1. Repeated Array Passes Simulation
Intuition
Repeatedly scan the array and simulate adjacent collisions (+ followed by -) until a full scan completes with zero collisions.
Algorithm
- Step 1: Convert the initial array into a dynamic list.
- Step 2: Start a loop with a boolean flag
hasCollided = true. - Step 3: Scan indices i from 0 to list.size() - 2. If list[i] > 0 and list[i+1] < 0, resolve the collision by removing the smaller or both, set
hasCollided = true, and restart the pass. - Step 4: Terminate when a complete pass finds no colliding pairs.
#include <iostream>#include <vector>#include <cmath> class Solution {public: std::vector<int> asteroidCollision(std::vector<int>& asteroids) { std::vector<int> res = asteroids; bool collided = true; while (collided) { collided = false; std::vector<int> nextPass; int n = res.size(); for (int i = 0; i < n; i++) { if (i < n - 1 && res[i] > 0 && res[i + 1] < 0) { collided = true; if (res[i] > std::abs(res[i + 1])) { nextPass.push_back(res[i]); } else if (res[i] < std::abs(res[i + 1])) { nextPass.push_back(res[i + 1]); } i++; // skip pair } else { nextPass.push_back(res[i]); } } res = nextPass; } return res; }}; int main() { Solution solver; std::vector<int> asteroids = {5, 10, -5}; std::vector<int> result = solver.asteroidCollision(asteroids); std::cout << "Result: ["; for (size_t i = 0; i < result.size(); i++) { std::cout << result[i] << (i + 1 < result.size() ? ", " : ""); } std::cout << "]" << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— In the worst case (e.g. [1, 2, 3, 4, -5]), each pass only resolves one collision and shifts the array, taking O(N) per pass across O(N) passes. - Space complexity:
O(N)— Requires O(N) auxiliary space to construct subsequent array states during passes.
Why Brute Force Doesn't Scale:
A chain reaction like [1, 2, 3, 4, 5, -6] triggers 5 separate array passes.
With N = 10,000, O(N2) takes ~108 operations, risking TLE.