[Codility] Lesson-03.1: FrogJmp

YeongHyeon Park
2 min readAug 25, 2020

--

In this post, the solution for lesson 3 with reducing time complexity is handled. For accessing the problem, click the following link.

Task Description

A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.

Count the minimal number of jumps that the small frog must perform to reach its target.

Write a function:

def solution(X, Y, D)

that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.

For example, given:

X = 10

Y = 85

D = 30

the function should return 3, because the frog will be positioned as follows:

  • after the first jump, at position 10 + 30 = 40
  • after the second jump, at position 10 + 30 + 30 = 70
  • after the third jump, at position 10 + 30 + 30 + 30 = 100

Write an efficient algorithm for the following assumptions:

  • X, Y and D are integers within the range [1..1,000,000,000];
  • X ≤ Y.

Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

Key Point

  • When the input X is equal or larger than Y, calculating the number of the jump is not need. Just return 0.
  • If not, the required number of jumps can be simply counted and through a ‘while’ or ‘for’ loop, but it is not efficient.

Solution (using Python)

def solution(X, Y, D):
if(X >= Y): return 0
else: return (Y - X) // D + int((Y - X) % D > 0)

Please use the above solution for reference.
I recommend you to write your own source code.

--

--

No responses yet