Thursday, July 20th
Detecting asteroid collisions is the problem of the day
Given an array of integers, where positive means motion to the right and negative to the left, figure out what asteroids remain after collisions, where the asteroid with the greater absolute value remains, while equal asteroids both explode.
Like many pairing problems, this problem can be solved with a stack
First we initialize the stack and a couple variables
Then iterate over all asteroids
Now if the top of the stack has an asteroid going right (positive) and the current asteroid is going left (negative), then we add logic to determine what explodes
If the absolute value of the top element is less than that of the asteroid, pop the stack until that is not the case
Else, if the two asteroids are of equal abs value, both explode
If the asteroid is smaller, set the add flag to false so it isn't added
To complete the logic, add the asteroid according to the add flag
Finally, add the elements of the stack to the answer vector in reverse
Thanks to the Editorial for clarifying how to add elements of the stack to the answer vector in reverse
Comments
Post a Comment