FastPrepLast Object Exit Time

Last Object Exit Time

IBM logoIBM● MediumINTERNOA
Learn

Problem statement

Several objects move along a table represented by the line segment from 0 to tableLength. For object i, position[i] is its distinct starting coordinate and velocity[i] is its nonzero signed velocity.

  • A positive velocity moves an object to the right.
  • A negative velocity moves an object to the left.
  • All objects start moving simultaneously at time 0.
  • When two objects collide, they instantly exchange velocities.
  • An object leaves the table after crossing either boundary.

Return the ceiling of the time when the final object leaves the table.

Function

lastObjectExitTime(tableLength: int, position: int[], velocity: int[]) → int

Examples

Example 1

tableLength = 9position = [2,4,5]velocity = [2,-2,4]return = 4

Because equal-mass collisions exchange velocities, the set of paths is equivalent to the objects passing through one another. Their independent exit times are 7/2, 4/2, and 4/4 seconds. The maximum is 3.5, whose ceiling is 4.

Constraints

  • tableLength > 0.
  • position.length == velocity.length and at least one object is present.
  • Every position[i] is strictly between 0 and tableLength.
  • No two objects have the same starting position.
  • Every velocity[i] is nonzero.
  • Collisions occur instantly.

More IBM problems

See IBM hiring insights
public int lastObjectExitTime(int tableLength, int[] position, int[] velocity) {
    // Write your code here
}
tableLength9
position[2,4,5]
velocity[2,-2,4]
expected4
Checking account…