Asteroid Collision

July 13, 2025

Question

You're given an array of integers representing asteroids moving along a line. Each number indicates the asteroid's size and direction:

When two asteroids collide, the smaller one explodes. If they're the same size, both explode.

Return the state of the asteroids after all collisions.

Example

Input: [-2, -2, 4, 2, -3, -3, -5]

Output: [-2, -2, -5]

Explanation:

My Notes

package main

import (
	"fmt"
)

type Stack struct {
	items []int
}

func (s *Stack) Push(item int) {
	s.items = append(s.items, item)
}

func (s *Stack) Pop() int {
	popped := s.items[len(s.items)-1]
	s.items = s.items[:len(s.items)-1]
	return popped
}

func (s *Stack) Top() int {
	return s.items[len(s.items)-1]
}

func (s *Stack) Empty() bool {
	return len(s.items) == 0
}

func asteroidCollision(asteroids []int) []int {

	stack := Stack{}

	for _, val := range asteroids {
		for !stack.Empty() && stack.Top() > 0 && val < 0 {
			if stack.Top() == -val {
				stack.Pop()
				val = 0
				continue
			} else if stack.Top() < -val {
				stack.Pop()
			} else if stack.Top() > -val {
				val = 0
			}
		}
		if val != 0 {
			stack.Push(val)
		}
	}

	return stack.items
}

func main() {
	result := asteroidCollision([]int{-2, -2, 4, 2, -3, -3, -5})
	fmt.Println(result)
}