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

    stack<int> stk;
    int asteroid;
    bool add_asteroid;

Then iterate over all asteroids

    for(int i=0; i<asteroids.size(); i++) {
        asteroid=asteroids[i];
        add_asteroid=true;
      
        ...
    }

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

    while(!stk.empty() && (stk.top()>0 && asteroid<0)  ) {
        ...
    }

If the absolute value of the top element is less than that of the asteroid, pop the stack until that is not the case

    if(abs(stk.top()) < abs(asteroid)) {
        stk.pop();
        continue;
    }

Else, if the two asteroids are of equal abs value, both explode

    else if( abs(stk.top())==abs(asteroid)) {
        stk.pop();
    }

If the asteroid is smaller, set the add flag to false so it isn't added

    add_asteroid=false;
    break;
}

To complete the logic, add the asteroid according to the add flag

    if(add_asteroid) stk.push(asteroid);

Finally, add the elements of the stack to the answer vector in reverse

    vector<int> answer(stk.size());
    int asz = answer.size();
    for(int i=asz-1; i>=0; i--) {
        answer[i]=stk.top();
        stk.pop();
    }
    return answer;

Thanks to the Editorial for clarifying how to add elements of the stack to the answer vector in reverse

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th