In this post, we will solve the Number Line Jumps HackerRank Solution. This problem (Number Line Jumps) is a part of the HackerRank Problem Solving series.
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 x1 and moves at a rate of v1 meters per jump.
- The second kangaroo starts at location x2 and moves at a rate of v2 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
.
Number Line Jumps Hacker Rank Solution
Problem solution in Python programming:
def kangaroo(x1, v1, x2, v2): # Write your code here if (x1 == x2): return "YES" if (v1 <= v2): return "NO" while (x1 <= x2): if (x1 == x2): return "YES" x1 += v1 x2 += v2 return "NO"
Problem solution in Java programming:
public static String kangaroo(int x1, int v1, int x2, int v2) { // Write your code here int i=0; int sum1 = x1 + v2; int sum2 = x2 + v2; while(i<10000){ if(sum1 == sum2){ return "YES"; } sum2+=v2; sum1+=v1; i++; } return "NO"; }
Problem solution in Javascript programming:
function kangaroo(x1, v1, x2, v2) { let isPossible = "NO" if(v1 > v2){ let i = 1 while(x1 + v1*i <= x2 + v2*i){ if(x1 + v1*i == x2 + v2*i){ isPossible = "YES" break } i++ } } return isPossible }
Leave a Reply