Intersection point of two functions

Constantino Mora
2 min readSep 20, 2020

I saw this problem in HackerRank that caught my attention and I liked it:

https://www.hackerrank.com/challenges/kangaroo/problem

“You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity).

  • The first kangaroo starts at location and moves at a rate of meters per jump.
  • The second kangaroo starts at location and moves at a rate of meters per jump.

You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES, otherwise return NO.

For example, kangaroo starts at with a jump distance and kangaroo starts at with a jump distance of . After one jump, they are both at , (, ), so our answer is YES.”

Example explained:

Given that the first kangaroo starts at position 0 and progresses 3 meters per jump, while the second kangaroo starts at position 4 and progresses 2 meters per jump, we can see that at the 4th jump they will meet each other.

Key to solve it:

If we consider the velocity and initial position for each Kangaroo as a pair of equations, to know at what point they meet each other is equivalent to knowing the intersection points of both functions.

If we consider:

f(j) = v1(j) + x1

and

g(j) = v2(j) + x2

Where “j” are the number of jumps,

then, the intersection points of f(j) and g(j) are those numbers “j” for which f(j) = g(j), hence:

v1(j) + x1 = v2(j) +x2

0 = v2(j)+x2-v1(j)-x1

Solve “j”:

0 = v2(j) -v1(j)+x2-x1

0 = (v2-v1)(j)+x2-x1

(x1-x2) = (v2-v1)(j)

(x1-x2)/(v2-v1) = j

If we plot these functions individually with some given values, for example:

We can see from the graphs that the intersection point is at: 4, 12

That means that it will take them 4 jumps to meet each other at meter 12.

So, to know the number of jumps needed we simply substitute with the given values in here:

j = (x1-x2)/(v2-v1)

It’s important to consider that the jumps should be positive and integers.

Happy coding!

--

--