Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this mean "Detected time complexity: O(Y-X)"?

I am doing some Codility coding practices and in the results, I got this "Detected time complexity: O(Y-X)". I do not understand what it actually means. It is because of my lousy and constant looping? How to enhance or improve the performance to get rid of this poor performance?

public static int Solution(int startPoint, int endPoint, int frogJumpPowerDistance)
{
            int jumpCount = 0;

            // AIM: return the number of jumps to reach endPoint

            // CHECK: no jump needed.
            if (startPoint == endPoint) return jumpCount;

            int distanceReach = startPoint + frogJumpPowerDistance;
            jumpCount++;
            if (distanceReach < endPoint)
            {
                //enter checking loop
                do
                {
                    distanceReach += frogJumpPowerDistance;
                    jumpCount++;
                }
                while (distanceReach < endPoint);
            }

            return jumpCount;
}

I expect not to get a Timeout error. But I got it.

I am not sure how to improve my codes to solve the Timeout error.

For the input (5, 1000000000, 2) the solution exceeded the time limit.

For your information,

  1. All inputs are within range [1 ... 1,000,000,000].

  2. startPoint less than or equal to endPoint.

like image 684
Min Avatar asked Mar 05 '23 00:03

Min


1 Answers

I think what "Detected time complexity: O(Y-X)" means is that it is saying your code takes longer to run when the start and end is farther apart. Specifically, the time it takes to run your code increases linearly with respect to the difference between start and end. Note that I am assuming Y is the end and X is the start.

You don't actually need a loop here. You can just do some maths to figure out how many jumps you need, and do this in constant time O(1).

First, you calculate the distance you have to jump by calculating the difference between start and end:

int distance = endPoint - startPoint;

Then, divide the distance by the jump power:

int jumps = distance / frogJumpPowerDistance;

If distance is divisible by frogJumpPowerDistance, then we can just return jumps. Otherwise, we still have some distance left, after we have jumped jumps times (this is integer division!). So we need one more jump to finish it off.

if (distance % frogJumpPowerDistance == 0) {
   return jumps;
} else {
   return jumps + 1;
}

EDIT:

As iakobski suggested in the comments, this can also be done with just one division, like so:

return (distance - 1) / frogJumpPowerDistance + 1;
like image 131
Sweeper Avatar answered Mar 15 '23 22:03

Sweeper