awelgorithms

Leave equal-strength annihilation

Updated

When magnitudes are equal and they oppose, both die: pop the top and do not push the newcomer. That is a third outcome besides top wins and newcomer wins.

What to focus on

Do not leave one of them. After annihilation the next top may still fight a later item, not this one. Equals with same direction do not annihilate. They never meet.

Worked examples

both die

a = [8, 5], incoming -5
  1. 5 vs 5
  2. pop 5
  3. do not push -5

Result: [8]

then stop

a = [8], after that annihilation
  1. -5 is gone
  2. do not apply the dead -5 to 8

Result: [8]

same dir equal

a = [5], incoming 5
  1. no oppose
  2. push

Result: [5, 5]

Try it

Write annihilate(stack, incoming). stack is the survivor stack. incoming is a non-zero integer. If they oppose and magnitudes are equal, pop the top and do not push incoming. Same-sign equals just stack. a = [8, 5], incoming -5 → [8]. a = [8], after that annihilation → [8]. a = [5], incoming 5 → [5, 5].

The stack starts non-empty. Incoming is a non-zero integer. Equal-magnitude oppose is in scope.