Skip to the code
cf.
+25 XP

#256 Colliding Cards on a Track

medium

An onboarding animation slides cards along one track, all at the same speed. Each card is a number in cards, in order along the track: the absolute value is its size, a positive number moves right, and a negative number moves left.

When a right-moving card meets a left-moving card, the smaller one disappears; if they are the same size, both disappear. Cards moving the same way never meet, and a left-moving card that has nothing to its left (or only left-moving cards) slides away safely.

Write afterCollisions(cards) that returns the cards left after every collision, in track order.

Example 1

Input: cards = [4,8,-3]
Output: [4,8]

8 and -3 meet and -3 disappears; 4 and 8 move the same way.

Example 2

Input: cards = [8,-8]
Output: []

Equal sizes: both disappear.

Constraints

  • 0 <= cards.length <= 10^4
  • -1000 <= cards[i] <= 1000
  • cards[i] !== 0
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).