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,
All inputs are within range [1 ... 1,000,000,000].
startPoint less than or equal to endPoint.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With