Minimum Speed to Arrive on Time

Find the slowest whole-number speed that gets you through a chain of trains within a time limit.

To reach the office you take n trains, one after another, and train i covers dist[i] kilometres. You choose one whole-number speed, in kilometres per hour, and every train runs at it. A train only departs on a whole hour, so after a ride that ends at 1.5 hours you wait until hour 2 for the next one. Given the limit hour, a decimal number with at most two digits after the point, return the minimum speed that gets you to the office within hour hours, or -1 if no speed is fast enough. The answer is promised to be at most 107.

Example 1
Input: dist = [1, 3, 2], hour = 6
Output: 1
Explanation: at speed 1, the rides take 1, 3 and 2 hours, so you arrive at exactly hour 6.
Example 2
Input: dist = [1, 3, 2], hour = 2.7
Output: 3
Explanation: at speed 3, the first ride takes 1/3 hour, then you wait until hour 1. The second ride takes 1 hour, and the last takes 2/3 hour, so you arrive at about 2.67.
Example 3
Input: dist = [1, 3, 2], hour = 1.9
Output: -1
Explanation: the first two trains take at least one whole hour each, so you cannot arrive before hour 2.
Solution

The Idea

You have probably waited on a platform for a train that leaves on the hour, even though you arrived early. That waiting is what makes this problem interesting. A faster train gets you to the next station sooner, but the next train still leaves at the same whole hour.

Take Example 2: three rides of 1, 3 and 2 kilometres, and 2.7 hours to do them. Look at the picture below. It shows the same trip at two speeds, with the limit hour = 2.7 as a dashed line.

The trip dist = [1, 3, 2] at speed 2 and speed 3, with the limit hour = 2.7. At speed 2 the trip ends at hour 4, late. At speed 3 it ends at 2.67, on time.

In the row labelled speed 2, the 1 km ride takes half an hour, and then you wait until hour 1. The 3 km ride takes 1.5 hours and ends at 2.5, so you wait again, until hour 3. The 2 km ride ends at hour 4: late.

In the row labelled speed 3, the 1 km ride ends at about 0.33, and you wait until hour 1. The 3 km ride takes exactly one hour, so the last train leaves at hour 2 with no wait. Its 2 km take 2/3 of an hour, and you arrive at 2.67: on time.

Notice that the last ride has no wait after it. You get off and walk to the office, so its time counts as an exact fraction. Every other ride counts as a whole number of hours, its time rounded up.

So for any one speed, we can work out the arrival time. But which speed should we try? Speeds go up to 107, far too many to try one by one. Here is what helps: going faster never makes you arrive later. Each ride gets shorter or stays the same, and so does each wait. If speed 3 is on time, so are 4, 5 and every faster speed. If speed 2 is late, so is speed 1.

Ask "is this speed on time?" for the speeds 1, 2, 3, 4 and so on, and the answers read no, no, yes, yes, and stay yes. We want the first yes. Finding where answers switch from no to yes, by halving the range of candidates at each guess, is called binary search, and here it runs over the speeds instead of over an array.

Solution Approach

Turning that idea into code means settling four things: how to time the trip for one speed, how to search the speeds, when to give up with -1, and how to compare times with the limit exactly.

Timing the trip for one speed

How long does the trip take at speed s? Every ride except the last takes dist[i] / s hours, rounded up to a whole hour because of the wait. The last ride takes exactly dist[n - 1] / s hours. The sum of these is the arrival time, which must not be more than hour.

Rounding up in whole numbers needs no fractions: (dist[i] + s - 1) / s in Java integer division gives dist[i] / s rounded up. For 3 km at speed 2 it gives 4 / 2 = 2, and for 3 km at speed 3 it gives 5 / 3 = 1.

Searching the speeds

The simple way is to try speed 1, then 2, then 3, until one is on time. Each try loops over all n trains, and the answer may be near 107, so that can mean ten million passes over the trains.

Binary search keeps a range from lo to hi that surely holds the answer, starting at 1 and 107. It tries the speed mid halfway between them. If mid is on time, the answer is mid or slower, so hi moves down to mid. If mid is late, the answer is faster, so lo moves up to mid + 1. When the two meet, they sit on the slowest speed that is on time. Each guess halves the range, so about 24 guesses cover ten million speeds.

When no speed works

Why can a trip be impossible at any speed? However fast the trains go, each ride except the last ends with a wait until the next whole hour. Each of those first n - 1 rides therefore costs at least one hour. In Example 3, two such rides need two hours, and 1.9 is less than that.

Since the answer is promised to be at most 107, one check settles it: if even speed 107 is late, return -1 before the search starts.

Comparing times exactly

The arrival time is a fraction, and adding fractions as double values can be off by a tiny rounding error. When the arrival time is exactly hour, that error can make an on-time speed look late. Since hour has at most two digits after the point, it can be stored in hundredths as a whole number, 2.7 as 270. The check is then:

wholeHours + last / speed <= limit / 100

Here wholeHours is the sum of the rounded-up rides, last is the last distance, and limit is hour in hundredths. Multiplying both sides by 100 * speed removes every division, so the comparison uses whole numbers only, in long to leave room for large values.

Java Solution

The method minSpeedOnTime works in these steps:

  1. First, set the search range: lo is 1 and hi is 10,000,000. Store hour in hundredths as limit, with Math.round(hour * 100).
  2. Ask the helper onTime whether speed hi is on time. If it is not, return -1.
  3. Then run a loop while lo is less than hi. Each round takes the speed mid halfway between them and asks onTime about it. On time moves hi down to mid, and late moves lo up to mid + 1.
  4. When the loop ends, lo equals hi, and it is the slowest speed that is on time. Return lo.

The helper onTime loops over every ride except the last and adds its rounded-up hours into wholeHours. Then it compares wholeHours plus the exact last ride with limit, with both sides multiplied by 100 * speed so only whole numbers are compared.

The main method runs the three examples, a single train with half an hour, a trip that needs the fastest allowed speed, and a trip whose arrival time is exactly the limit.

Java
public class MinimumSpeedToArriveOnTime {

    public static int minSpeedOnTime(int[] dist, double hour) {
        int lo = 1;
        int hi = 10000000;                  // the problem promises the answer is at most 10^7
        long limit = Math.round(hour * 100);  // hour in hundredths: it has at most two decimals
        if (!onTime(dist, hi, limit)) {
            return -1;                        // not even the fastest allowed speed is enough
        }
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (onTime(dist, mid, limit)) {
                hi = mid;                     // mid is fast enough: the answer is mid or slower
            } else {
                lo = mid + 1;                 // mid is too slow: the answer is faster
            }
        }
        return lo;
    }

    // Every train except the last leaves on a whole hour, so round those rides up.
    // Checks wholeHours + last / speed <= limit / 100, multiplied out by 100 * speed.
    private static boolean onTime(int[] dist, int speed, long limit) {
        long wholeHours = 0;
        for (int i = 0; i < dist.length - 1; i++) {
            wholeHours += (dist[i] + speed - 1) / speed;   // dist[i] / speed, rounded up
        }
        return 100 * (wholeHours * speed + dist[dist.length - 1]) <= limit * speed;
    }

    public static void main(String[] args) {
        System.out.println(minSpeedOnTime(new int[] {1, 3, 2}, 6));
        System.out.println(minSpeedOnTime(new int[] {1, 3, 2}, 2.7));
        System.out.println(minSpeedOnTime(new int[] {1, 3, 2}, 1.9));
        System.out.println(minSpeedOnTime(new int[] {7}, 0.5));
        System.out.println(minSpeedOnTime(new int[] {1, 1, 100000}, 2.01));
        System.out.println(minSpeedOnTime(new int[] {11, 78368}, 1.64));
    }
}

Running it prints:

Output
1
3
-1
14
10000000
122450

The first three lines give 1, 3 and -1, the answers of the three examples. The fourth line, 14, comes from one train of 7 km with half an hour. With only one train there is no wait at all, and 7 km in half an hour needs exactly 14 km per hour.

The fifth line, 10000000, is the trip [1, 1, 100000] with 2.01 hours. The two short rides cost one whole hour each, which leaves 0.01 hours for 100,000 km, so only the fastest allowed speed works.

Look at the last line, 122450, for [11, 78368] with 1.64 hours. At that speed the 11 km ride is rounded up to one hour, and 78368 / 122450 is exactly 0.64, so you arrive at exactly 1.64. Summed as double values, that time comes out as 1.6400000000000001. A version that compares double sums with hour therefore calls 122450 late and returns 122451. The whole-number check in onTime keeps the correct answer.

Complexity

The work is one call to onTime for the -1 check, plus one call for each guess of the binary search.

  • Time: O(n log 107), where n is the number of trains. Halving the range of 107 speeds takes about 24 guesses, and each onTime call loops over all n distances once.
  • Space: O(1). onTime adds into one long, and the search keeps only lo, hi and mid, however many trains there are.

The same search for the smallest speed that is fast enough appears in Koko Eating Bananas, where every pile is rounded up and nothing is left as an exact fraction.