Kangaroo HackerRank Solution in C/C++/Java/Python

In HackerRank Challenges, the number line jumps problem states the location of starting point of two kangaroos on the number line (x1 & x2). Both Kangaroos have their own jump velocity – v1 & v2 metres per jump. And when both kangaroos land at the name location on the number line after same number of jumps then you have to print ‘YES’ else ‘NO’.

When I solved the problem I found two cases to be taken care of –
1. The starting point of both the kangaroos are different. So, forming a case where the kangaroos do not meet is very important. Logic – the kangaroo1 who is ahead of kangroo2 on number line should have speed less than kangroo2 for them to meet at anytime ahead and Vice Versa.
2. The second case to take will be the meeting point. Make sure the number of jumps and the meeting point on the number line is same.

Number Line Jumps or Kangaroo Jumps HackerRank Challenge

Sample Input 0

0 3 4 2

Sample Output 0

YES

Sample Input 1

0 2 5 3

Sample Output 

NO

 

Kangaroo HackerRank Solution in C++

#include <bits/stdc++.h>
using namespace std;

int main(){
int sp1,j1,sp2,j2; 
cin>>sp1; //starting point kangaroo1
cin>>j1; //jump velocity kangaroo1
cin>>sp2; //starting point kangaroo2
cin>>j2; // jump velocity kangroo2

while(true)
{
if( sp1>sp2&&j1>j2 || sp2>sp1&&j2>j1 || j1==j2)
{
cout<<"NO";
break;
}
if ((sp1=sp1+j1)==(sp2=sp2+j2))
{
cout<<"YES";
break;
}
}
return 0;
}

 

Kangaroo HackerRank Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
int x1; 
int v1; 
int x2; 
int v2; 
scanf("%d %d %d %d",&x1,&v1,&x2,&v2);
if(x2>x1){
if(v2<v1){
if((x2-x1)%(v1-v2)==0)
printf("YES");
else
printf("NO");
}
else
printf("NO");
}
else{
if(v1>v2){
if((x1-x2)%(v2-v1)==0)
printf("YES");
else
printf("NO");
}
else if(x1==x2&&v1==v2)
printf("YES");
else
printf("NO");
}
return 0;
}

 

Kangaroo HackerRank Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x1 = in.nextInt();
int v1 = in.nextInt();
int x2 = in.nextInt();
int v2 = in.nextInt();

if (v1>v2&&(x2-x1)%(v1-v2)==0)
System.out.println("YES");
else
System.out.println("NO");
}
}

 

Kangaroo HackerRank Solution in Python

#!/bin/python

import sys

x1,v1,x2,v2 = raw_input().strip().split(' ')
x1,v1,x2,v2 = [int(x1),int(v1),int(x2),int(v2)]
if v1==v2:
print 'NO'
else:
if (x1-x2+v2-v1)%(v2-v1)==0:
if (x1-x2+v2-v1)/(v2-v1)>0:
print 'YES'
else:
print 'NO'
else:
print 'NO'

 

Attempt Kangaroo HackerRank Challenge
Link : https://www.hackerrank.com/challenges/kangaroo

1 thought on “Kangaroo HackerRank Solution in C/C++/Java/Python”

Leave a Comment