Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Asteroid Collision

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "735" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

We are given an array asteroids of integers representing asteroids in a row. The indices of the asteriod in the array represent their relative position in space. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Example 1: Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8,-8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10,2,-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. Constraints: 2 <= asteroids.length <= 104 -1000 <= asteroids[i] <= 1000 asteroids[i] != 0

Explanation

Here's the breakdown of the solution:

  • Stack-based collision resolution: Use a stack to simulate the asteroid movements. Push asteroids onto the stack. If a negative asteroid encounters a positive asteroid on the stack's top (representing a collision), resolve the collision based on their sizes.
  • Handle continuous collisions: Continue resolving collisions until the stack is empty or the top element is no longer a positive asteroid.
  • Result extraction: The final state of the asteroids will be the elements remaining in the stack.

  • Runtime Complexity: O(n), where n is the number of asteroids. Storage Complexity: O(n) in the worst case (no collisions).

Code

    def asteroid_collision(asteroids):
    stack = []
    for asteroid in asteroids:
        while stack and asteroid < 0 and stack[-1] > 0:
            top = stack[-1]
            if top < abs(asteroid):
                stack.pop()
            elif top == abs(asteroid):
                stack.pop()
                asteroid = 0  # Mark asteroid for removal
                break
            else:
                asteroid = 0  # Mark asteroid for removal
                break
        if asteroid != 0:
            stack.append(asteroid)
    return stack

More from this blog

C

Chatmagic blog

2894 posts