Last Moment Before All Ants Fall Out of a Plank

Last Moment Before All Ants Fall Out of a Plank

This is the Medium level question of Leetcode Link.

But it's kind of Easy problem when you get it once.

This question asked in Google.

Problem

We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.

When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time.

When an ant reaches one end of the plank at a time t, it falls out of the plank immediately.

Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.

Example 1:

Input: n = 4, left = [4,3], right = [0,1]
Output: 4
Explanation: In the image above:
-The ant at index 0 is named A and going to the right.
-The ant at index 1 is named B and going to the right.
-The ant at index 3 is named C and going to the left.
-The ant at index 4 is named D and going to the left.
The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).

Explanation

Take two ANT and which are moving in the opposit direction, so as per the question.
The posititon of the ants before and after the collision is following :-

Before collision**: (B)-> <-(C)**
After collision : <-(C) (B)->

But if we ignore that ANT are changing the direction, on collision.

Before collision : (B)-> <-(C)
After collision : <-(B) (C)->

(Arrow representing the moving direction of the particular ant)

Like this at time = 1.5s and 2s. The ANT B and C , interchanged it's direction.

So we can ignore the ANTs are moving in in one line, as we have to find the last to fall out from the pland

Hence we can ignore this changing the direction, in order to find the which Ant is going to fall last.

Approach

So now we have to find that which ant is more far from it's moving direction plank end.

So we gonna calculate by iterating through each ant position and we'll find it.

Complexity

  • Time complexity: O(n)

  • Space complexity: O(1)

Code

class Solution {
    public int getLastMoment(int n, int[] left, int[] right) {
        int ans = 0, max = Integer.MIN_VALUE;

        for(int a: left)    max = Math.max( a, max);
        for(int a: right)   max = Math.max((n - a), max);

        return max;
    }
}

Did you find this article valuable?

Support Anurag's blog by becoming a sponsor. Any amount is appreciated!