LeetCode 75

Asteroid Collision

Problem
LC 735
Topic
Stack
File
official75_LC735AsteroidCollision.java
Path
pkg5leetcode/official75/official75_LC735AsteroidCollision.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC735AsteroidCollision.java
Approach
Stack simulate collisions by direction and size.
Complexity
Time O(n), Space O(n)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC735AsteroidCollision.java
1package pkg5leetcode.official75;2 3/*4 * Asteroid Collision | LC 7355 * APPROACH: Stack simulate collisions by direction and size.6 * COMPLEXITY: Time O(n), Space O(n)7 */8import java.util.*;9 10public class official75_LC735AsteroidCollision {11    static int[] asteroidCollision(int[] asteroids) {12        Deque<Integer> st = new ArrayDeque<>();13        for (int a : asteroids) {14            boolean alive = true;15            while (alive && a < 0 && !st.isEmpty() && st.peekLast() > 0) {16                int top = st.peekLast();17                if (top < -a) st.pollLast();18                else if (top == -a) { st.pollLast(); alive = false; }19                else alive = false;20            }21            if (alive) st.addLast(a);22        }23        return st.stream().mapToInt(Integer::intValue).toArray();24    }25 26    public static void main(String[] args) {27        check(Arrays.equals(asteroidCollision(new int[]{5,10,-5}), new int[]{5,10}), "case1");28        check(Arrays.equals(asteroidCollision(new int[]{8,-8}), new int[]{}), "case2");29        check(Arrays.equals(asteroidCollision(new int[]{10,2,-5}), new int[]{10}), "case3");30        System.out.println("all tests passed");31    }32 33    static void check(boolean cond, String name) {34        if (!cond) throw new AssertionError("FAILED: " + name);35        System.out.println("  PASS " + name);36    }37}