Problem · Stack
MediumMathWorksOA

Problem statement

There are n toy cars on a road. Their indices describe their initial order from left to right.

  • direction[i] = 1 means car i moves right.
  • direction[i] = -1 means car i moves left.
  • strength[i] is the strength of car i.

When two cars collide, the car with lower strength is destroyed. If their strengths are equal, both cars are destroyed. A surviving car continues moving in its original direction, so it may collide again.

Return the zero based indices of all surviving cars in increasing order after every possible collision.

Function

carsLeft(n: int, direction: int[], strength: int[]) → int[]

Examples

Example 1

n = 3direction = [1, -1, 1]strength = [5, 3, 2]return = [0, 2]

Car 0 moves right and car 1 moves left. Since strength[0] = 5 is greater than strength[1] = 3, car 1 is destroyed. Car 2 moves right and does not face another car, so the survivors are [0, 2].

Example 2

n = 6direction = [1, -1, -1, 1, -1, 1]strength = [7, 2, 3, 5, 5, 6]return = [0, 5]

Car 0 destroys cars 1 and 2 because its strength is greater than both of theirs. Cars 3 and 4 have equal strength, so both are destroyed. Car 5 moves right and survives. The surviving indices are [0, 5].

Constraints

  • n <= 2 * 10^5
  • direction[i] = 1 or direction[i] = -1
  • strength[i] <= 10^9

More MathWorks problems

drafts saved locally
public int[] carsLeft(int n, int[] direction, int[] strength) {
  // write your code here
}
n3
direction[1, -1, 1]
strength[5, 3, 2]
expected[0, 2]
checking account