- Practice
- Algorithms
- Implementation
- Kangaroo
- Discussions

# Kangaroo

# Kangaroo

Mily94 + 71 comments well, I think it is much easier than we think... We just need solve equation : x1 + y * v1 = x2 + y * v2 where "y" is number of jumps... so if (x1 - x2) % (v2 - v1) == 0 then our kangaroos will meet each other : )

jigarjani + 4 comments Whoa.. Bam!! Didn't think that. Still need to take care of things like zero and negative.

rolfbuch + 4 comments The problem states that x2 is strictly greater than x1.

Thus, if v2 == v1 then the answer is "NO".

Thus, both x2-x1 and v1-v2 are guaranteed positive and non-zero.

Interpretitis + 3 comments The expression (v2 - v1) is not guaranteed to be positive as the speed of the second roo could be greater than the first. However, for a YES solution the expression (x1 - x2) / (v2 - v1) must be a positive integer.

rolfbuch + 0 comments [deleted]rolfbuch + 0 comments [deleted]rolfbuch + 3 comments (Been having trouble submitting comments, sorry if this comes through multiple times. Also, you state v2-v1 is not guaranteed to be positive, which is true. I believe you meant v1-v2, which I address below.)

The problem states that X2 > X1, so if V2 >= V1 then there is no solution.

Therefore, for any data that we will operate on (V1-V2) is guaranteed to be positive.

ibrahimker + 21 comments `int k1 = x1; int k2 = x2; if(x2>x1&&v2>v1){ System.out.print("NO"); } else{ for(int i=0;i<10000;i++){ k1+=v1; k2+=v2; if(k1==k2){ System.out.print("YES"); System.exit(0); } } System.out.print("NO"); }`

ez

Meenachinmay + 2 comments looping 10000 times...dont you think its a brute force like approach i also thought the same idea but didnt apply for the same reason...we can make a logic to solve this nahhhh????

P1zzAdr0hn3 + 0 comments [deleted]mohan_pierce007 + 1 comment function kangaroo(x1, v1, x2, v2) { var difference=0;

`var calculate=function(){ if((x1<x2)&&((v1<v2)||(v1==v2))){ return "NO" } else{`

while(Math.sign(difference)!=-1){ x1+=v1; x2+=v2; difference=x2-x1; if(difference==0){ return "YES" } } return "NO" } }(); return calculate; }

Check the difference between the two kangaroos on each jump if they come to become 0 then yes or no if the difference goes to negative-This is the main logic other anomaly is if both distances are equal from start theyll never produce negative or 0 so print no and see if the second kangaroo is way ahead than the first one from start if yes then print "No"

Javascript

apatial27 + 0 comments good logic

DavidZhai + 1 comment This is not optimal due to two reasons: 1. you have a minimum of 10,000 loops (which for many problems will take way longer than they need to solve) 2. Suppose it takes 10,001 steps for the kangaroos to be on the same spot. This might not be a mathematically possible case given the constraints, but for a bigger problem size it might. I think in general it is not good to introduce arbitrary large numbers for looping through, given the possibility of potential weird subtle bugs when scaling the code up. (Although of course this is just a practice problem so doesn't necessarily apply).

Given all that, you can still keep most of your code with the change of the for(10000) into a while (x1 < x2). This suggests that once the left kangaroo passes the right kangaroo, they'll never meet because they have fixed velocities. There might be some other subtle changes you need, but this is a good starting point. Good luck!

mohan_pierce007 + 0 comments Will this be optimal?

function kangaroo(x1, v1, x2, v2) { var difference=0; var calculate=function(){ if((x1<x2)&&((v1<v2)||(v1==v2))){ return "NO" } else{ while(Math.sign(difference)!=-1){ x1+=v1; x2+=v2; difference=x2-x1; if(difference==0){ return "YES" } } return "NO" } }(); return calculate; }

Check the difference between the two kangaroos on each jump if they come to become 0 then yes or no if the difference goes to negative-This is the main logic other anomaly(Infinite looping problem) is if both distances are equal from start theyll never produce negative or 0 so print no and see if the second kangaroo is way ahead than the first one from start if yes then print "No"

trungtlt + 4 comments why 10.000??? these kangarooes can jump to infinity, your ans abs can not solve this problem

paul_schmeida + 1 comment Exactly, 10k is the maximum jump distance for 1 jump, there's no limit on number of jumps.

It can be solved by looking for same position at the nth jump until the kangaroo that was behind gets in front of the other. The guy gave the equation in the first comment, after checking for impossible combinations just use that equation.

gkjha009 + 1 comment I did the same, and it worked. No need to run loop in vein.

if( x2>x1 && v2>v1) return "NO";

`let result = (x1-x2) % (v2-v1); if( result === 0){ return "YES"; } return "NO";`

jossdean + 0 comments nice!

i applied the remander (mod %) after calcultion (x2-x1 / (v1-v2) ... your is nice and ismple

girish_sharma_01 + 0 comments yes you are right.

lindanordstrom86 + 2 comments There is no limit to jumps, BUT there are constraints to their distance between them and jump length, right? So by taking the "worst case" scenario which would be:

x1 = 0

v1 = 2

x2 = 10000

v2 = 1

it will take 10 000 jumps for the first kangaroo to catch up with the other one, any more jumps is impossible under these constrainst, therefor the loop solution is valid.

But, I agree that the "(x1 - x2) % (v2 - v1) == 0" solution is neater ;)

bgreenfield + 0 comments [deleted]ben_nxumalo + 0 comments you will need to add validation for division by ZERO PHP version that worked for me if((v1 && x2)||(x2 && v2)) return "NO"; elseif(x2 || v2) return "NO"; elseif((x2) % (v1) == 0) return "YES"; return "NO";

NiceBuddy + 1 comment this passed all tests even it runs almost 10K times!

#include <bits/stdc++.h> using namespace std; string kangaroo(int x1, int v1, int x2, int v2) { // Complete this function string Ans="Not yet decided!"; if( (v1>v2 && x1<x2) || (v1<v2 &&x1>x2) ) { for(unsigned int i=0; i<10000; i++) { x1=x1+v1; x2=x2+v2; if(x1==x2) { Ans="YES"; return Ans; } } Ans="NO"; return Ans; } else { Ans="NO"; return Ans; } }

nav293 + 1 comment I passed all testcases and didn't even use a loop.

iylamsriramteja + 1 comment will u send me the code i passed only 19 test cases

nav293 + 5 comments if(v2>=v1 && x1!=x2){ return "NO"; } else{ float x = (float)(x2-x1)/(v1-v2); if( floor(x) == x ) return "YES"; else return "NO"; }

zakiralig184 + 1 comment [deleted]zakiralig184 + 1 comment [deleted]zakiralig184 + 0 comments In constraint it is given that X1 is less than X2, therefore, there is no need to check X1 isn't equal to X2.

ssaulakh2 + 0 comments Can you expalin your code so others can learn?

praveenbisht390 + 2 comments what's floor(x)??

Beeksie + 0 comments It is a method that gives the largest integer that is less than or equal to the argument.

tejaasvenkatesh + 0 comments To check whether (x2-x1)/(v2-v1) is a perfect integer, he considered the float value and floor value of it. Floor gives the number that is less than original number. 15.4 gives 15. -13.2 gives -14

kashish25798 + 0 comments [deleted]fimaruf + 0 comments a small correction for this scenario (v2 & x2)

if (v1 && x2) { return "NO"; } else { (float)x2 - v1 - d) == $d) return "YES"; else return "NO"; }

Mumthas_43 + 16 comments I think this is an easier solution N it works for all the cases

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

Wafflenaut + 4 comments By the definition of the problem, x1 is always less than x2 - so no need to test for that in your first if statement. Otherwise it looks good.

ankitmishra7991 + 0 comments [deleted]ankitmishra7991 + 0 comments [deleted]ankitmishra7991 + 0 comments [deleted]panjama231 + 1 comment - "By the definition of the problem, x1 is always less than x2"
- I don't see where this is stated in the problem.

mauroz771 + 1 comment Look at the first constraint in the statement: 0 <= x1 < x2 <= 10000

panjama231 + 0 comments Okay, thank you.

I will try to pay better attention to the constraints next time.

danislav_kirov + 7 comments You can do it with only one if-else statement:

if(v1 > v2 && !((x2-x1)%(v1-v2))) printf("YES"); else printf("NO");

This works for all test cases.

jefflima + 1 comment This solution will work for C/C++ because any number other than zero returns false. For Java:

f(v1 > v2 && ((x2-x1)%(v1-v2) == 0)) printf("YES"); else printf("NO");

That will work any case.

omarsamy09 + 1 comment can you explain please ?

arungov + 1 comment i think...

// given that x2 > x1, if v1 > v2 its a NO because kangaroo2 is already behind and cannot catchup by going slower than kangaroo1

// x2-x1 % v1-v2 this basically checks if the diff in the inital lead (x2-x1) can be made up by going faster

wyrlvillazorda + 1 comment why v1 < v2 is always false? can u explain?

karatedog + 0 comments - x2 is always greater than x1 -> the second kangaroo is always ahead of the first kangaroo
- v1 < v2, it means v2 is greater than v1, so the second kangaroo is faster than the first
- conclusion: if the second kangaroo is ahead of the first kangaroo and he is faster, then the first kangaroo can never catch up to the second kangaroo

kencluff + 0 comments Nice!

ammwaheed + 0 comments Can you please explain your algorithm?

bhindekishan99 + 1 comment when v1=v2 and x1=x2 for this case also ouput is "YES"

dai_co + 0 comments how can x1 = x2 if x1 < x2?

cs_nguyenhuudat + 0 comments why v1 > v2 and !(x2-x1)%(v1-v2) can you explain to me, plz! and if the text is (4 2 0 3) at that time v1 < v2 but it still true ??

Beeksie + 1 comment Can you explain why we use (x2-x1)%(v1-v2)? What is the logic behind this?

r_regueiro_sant1 + 0 comments % means module. If the % !== 0 then (x2-x1) the diference between both start points it's not divisible with (v2-v1) the diference of speed then they never will land on the same spot at the same time. 4%2 is 0 5%2 = 1 because 5/2 is 2*2 + 1

anuragccsu + 0 comments The solution is elegant but it assmues that x2 is > then x1 which is not mentioned in the problem and also dont handle the case of v1 == v2 so i modified it:

if ((v1 == v2) && !(x1 != x2)) printf("NO"); if(v1 > v2 && !((x2-x1)%(v1-v2))) printf("YES"); else if(v2 > v1 && !((x1-x2)%(v2-v1))) printf("YES"); else printf("NO");

ankitmishra7991 + 0 comments [deleted]ervaibhavkumar + 1 comment How this expression come to ur mind ? could u plz explain this expression ((x2-x1)%(v1-v2))==0)

beastieric + 9 comments If the two kangaroos met, then there woulde be an integer n such that x1 + n * v1 = x2 + n * v2. Subtracting x1 from both sides, we get that n * v1 = x2 - x1 + n * v2. Then we subtract n * v2 from both sides and we get n * v1 - n * v2 = x2 - x1. Factoring out n from the left side of the equation, n * (v1 - v2) = (x2 - x1). We can the divide both sides by (v1 - v2) and we get (x2 - x1) / (v1 - v2). If this is an integer, then (x2 - x1) % (v1 - v2) has to equal 0.

egarcia405 + 1 comment is n considered to be the same amount of jumps both kangaroo take?

IMCorey + 0 comments Yes. That's exactly what we need, the 'n' to be the same for both, so yes, n refer to the both kangaroos jump.

ibarry + 0 comments @beastieric. You are a beast. God Bless You!

marcusalexander + 0 comments thanks for the explanation. it helped me alot

sminmgr + 1 comment If this is an integer, then (x2 - x1) % (v1 - v2) has to equal 0. Can you explain this statement, I didn't get it.

karatedog + 2 comments "%" is the modulo operation, not division. When the modulo is 0, it means that dividing (x2 - x1) by (v1 - v2) has no remainder -> that is: (v1 - v2) can divide (x2 - x1) by a whole number of times.

sminmgr + 1 comment Oh thanks

edwinjo466 + 0 comments thanks @bosteric

shubham4230 + 0 comments If the two kangaroos met, then there woulde be an integer n such that =>x1 + n * v1 = x2 + n * v2 =>n * v1 = x2 - x1 + n * v2 =>n * v1 - n * v2 = x2 - x1 =>n * (v1 - v2) = (x2 - x1) =>n=(x2 - x1) / (v1 - v2) If this is an integer, then (x2 - x1) % (v1 - v2) has to equal 0.

victorkurauchi + 1 comment nice explanation! one thing i noticed running the tests was that with this input 0 2 5 3, the v1 - v2 is negative so we should consider that

if (v1-v2 > 0 && (x2-x1) % (v1-v2) == 0) { console.log('yes'); }

bthompson4163 + 0 comments That worked for me, I initially did the while loop way, and then got timeouts, so was trying to think of another way before coming to the discussion. I knew it would have to have something to do with some comparison having a modulo == 0, just couldn't quite get the equation.

kharatpriyank + 0 comments Thank you!

dheepthisb + 0 comments Thank you for the explanation!

tanmay777 + 0 comments Lovely Man!

arvindj19962014 + 0 comments Great explanation.. thanks a lot

sharma486 + 0 comments great solution.

djangodude + 2 comments what does this ((x2-x1)%(v1-v2) == 0) do? can you please explain?

beastieric + 0 comments This statement checks if x2-x1 is divisible by v1-v2.

shubham4230 + 1 comment If the two kangaroos met, then there woulde be an integer n such that =>x1 + n * v1 = x2 + n * v2 =>n * v1 = x2 - x1 + n * v2 =>n * v1 - n * v2 = x2 - x1 =>n * (v1 - v2) = (x2 - x1) =>n=(x2 - x1) / (v1 - v2) If this is an integer, then (x2 - x1) % (v1 - v2) has to equal 0.

fanjavaid + 1 comment What is n means?

tincumagic + 0 comments n is the number of jumps until kangoroos meet

weitzhandler + 0 comments Checking for

`x1<x2`

is redundant, it's one of the problem's constraints.bug_lover + 0 comments I think that in if((x1

nimish_gupta + 0 comments @Mumthas_43 how did you get this logic.

shoelessLawrence + 0 comments Well YES -> Mumthas_43!

`static string kangaroo(int x1, int v1, int x2, int v2) { // Complete this function string _return = "NO"; if (v1<v2) { ; } else { if((v1!=v2) && ((x2-x1)%(v1-v2))==0) { _return = "YES"; } } return _return; }`

sanjay311999 + 2 comments Still the code can be trimmed like this

if(v1<=v2) cout<<"NO"; else { if((x2-x1)%(v1-v2)==0) cout<<"YES"; else cout<<"NO"; }

maheshm121 + 0 comments can you please explain why (x2-x1)%(v1-v2)==0

sliu8 + 0 comments This is in fact wrong. If a was ahead of b even with a lower speed a and b could be at the same spot.

ravi_4800 + 0 comments ryt..i'ts an easier soln

pavanmurgan + 1 comment if i give x1 = 0, v1 = 1, x2 = 0, v2 = 1 this solution fails

shubham4230 + 0 comments given in the question x2 is strictly larger than x1( i.e x2 > x1)

prudhvi1 + 3 comments what if the case x1=x2 and v1=v2

NiceBuddy + 0 comments yes you are right: my program gives for this NO which is not correct. I do nt know then how it passed all cases!

if(x1==x2 && v1==v2) { Ans="YES"; return Ans; }

well adding this will cover that case too. and this time as well I passed all test cases! https://www.hackerrank.com/challenges/kangaroo/submissions/code/61681975

Zinuxs_Torvalds + 0 comments As the problem states a Constraint that x1<x2(in all the possible test cases),I didn't take that case into consideration and btw if x1!=x2 then for both the kangaroo to be at the same postion at the same time it is obvious that v1>v2(or take it as v1!=v2 as the if condition will look after v1<v2).Hope I sloved your query!!

shubham4230 + 0 comments See the constraints X2>x1(always)

johnmensah + 0 comments python version. slightly similar but different

def kangaroo(x1, v1, x2, v2): if((x1>x2 and v1>v2) or (x1<x2 and v1<v2) or (v1-v2)==0): return "NO" if((x1 - x2) % (v2 - v1)) == 0: return "YES" else: return "NO"

apatial27 + 0 comments great

19soumikrakshi96 + 3 comments Your logic is wrong. The correct brute force approach is: 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(); int c=0; int k1 = x1; int k2 = x2; if(x2>x1&&v2>v1) System.out.print("NO"); else { for(int i=0;i<10000;i++) { k1+=v1; k2+=v2; if(k1==k2) { c++; break; } } if(c!=0) System.out.print("YES"); else System.out.print("NO"); } }`

}

Sufiyan + 1 comment As mentioned in other answers, the number of jumps are infinity. X-axis is of infinity. We can't limit it to 10000.

uebu_nogami + 0 comments Yes, we can: the initial distance between kangaroos is at most 10000, and each jump makes them at least 1 'distance-unit' closer (if not, they will never meet anyway, this means that the speeds are 'not good').

(But I was too lazy to write the loop instead of doing simple math ^_^)

karadeniz + 0 comments I think it's better if your first if statement contains v2>=v1 instead of v2>v1. When v1 == v2 there is no need to calculate anything because kangaroo1 is always behind, they never catch each other.

iamuday + 0 comments good logic

Appurba + 1 comment x1, v1, x2, v2 = map(int, input().strip().split()) count = 0 for i in range(10000): if v2> v1: break

`x1 += v1 x2 += v2 if x1 == x2: print('YES') count += 1 break if x1 > x2 : break`

if count == 0: print('NO')

A_Pushpendra + 0 comments if second case i.e x1>x2 is true , considering initially x1

surya_palla1 + 0 comments Good logic bro , i missed the second no case

niveditha_v + 3 comments this works and not x1<10000 or x2<10000 , dont know why !

if(x1>x2 && v1>=v2) cout<<"NO"; else { for(;x1<100000000,x2<100000000;x1+=v1,x2+=v2) { //cout<<x1<<'-'<<x2<<endl; if(x1==x2){ f=1; break;} } if(f==1) cout<<"YES"; else cout<<"NO";

arjun1321 + 0 comments because that condition is only for initial position, not for final position. the final position can be greater than 10000

princevishal14 + 0 comments [deleted]prikshits100 + 0 comments very good

akarsh22 + 1 comment looping it till 10000 is not a solution as for large dataset it can take more than that

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

schordia + 0 comments The condition I used for the for loop was

for(int n = 1; !((v1>v2 && n*v1 + x1 > n*v2+x2)|| v1

The reason for this is that if the greater velocity has already exceeded the smaller velocity in distance there is no way the smaller velocity can ever catch up or meet the greater velocity. However, some of the test cases timeout because of this condition.

Xedinaska + 1 comment Oh...typical java-developer solution :)

*Guys, just remember that answer anytime you think "wtf, why this java app so slow" or "where is my f***ng RAM??!"dhingra_shubham1 + 0 comments That's racist.

wyrlvillazorda + 0 comments same with me,..

MikeJM + 0 comments In mathematical proof, even if 1 billionth case passes, that doesn't mean the next one will pass for sure.

_yash_agarwal_ + 0 comments you can use while loop.it is much more effective than 10000 iterations.. OR you can loop until x1 is greater than x2.

if(v2>=v1) { cout<<"NO"; } else { while(x1<=x2) { x1+=v1; x2+=v2; if(x1==x2) {cout<<"YES"; flag=1;} } if(flag==0) cout<<"NO"; }

masoumeh_jafari1 + 2 comments I think it is better to solve it this way:

string kangaroo(int x1, int v1, int x2, int v2) { // Complete this function // x1+m*v1=x2+mv2 => m=(x1-x2)/(v2-v1) , m is steps and //m should not be negetive and //remainder should be zero int x=x1-x2; int v=v2-v1; if(v!=0){ if(x%v==0 && x/v>0){ return "YES"; }else {return "NO";} }else {return "NO";} }

It works

Shakil335 + 0 comments Thanks . It works.

static String kangaroo(int x1, int v1, int x2, int v2) { // Complete this function String result1=""; int c=0; if(x2>x1 && v2>v1){ result1= "NO"; } else{ for(int i=0;i<4;i++){ x1=x1+v1; x2=x2+v2; if(x1==x2){ c++; break; } } if(c!=0){ result1="YES"; } else{ result1="NO"; } } return result1; }

This is my code it cant passes 4 test cases . So what is the problem .Can anyone explain?

straho1111 + 0 comments amazing

s28_170040431 + 0 comments CORRECT OR WRONG

vivu493 + 0 comments This is Einstein's works.

zakiralig184 + 0 comments C src code without using for loop scanf("%ld%ld%ld%ld",&x1,&v1,&x2,&v2); if(v2>=v1) printf("NO"); else { ((x2-x1)%(v1-v2)!=0)?printf("NO"):printf("YES"); }

It has PASSED ALL TEST CASES. It will control time complexity.

surendraps007 + 0 comments Are you checking the number of jumps also should be equal I did not find any jump condition in your code.

yashpatel7025 + 0 comments for(i=1;((v1>v2 && av1 && b

django_ + 0 comments let it go type of solution!

saininavn007 + 0 comments USE THIS NO NEED FOR LOOP UPTU 1000 OR MORE.... string kangaroo(int x1, int v1, int x2, int v2) { int k=v1; int l=v2; int sum1=v1+x1; int sum2=v2+x2; while(1) {

`if((sum1>sum2)&&(v1>v2)) return "NO"; else if((sum2>sum1)&&(v2>v1)) return "NO"; else { if(sum1==sum2) return "YES"; else { sum1=sum1+v1; sum2=sum2+v2; } }`

}

}

B_R_A_T_WOLF + 0 comments how we'll make sure that the kangaroos had made same no.. of jump...???

aivi9891 + 0 comments Thaank you sooo much on that!!!

maximshen + 1 comment Incorrect. (v1-v2) is NOT guaranteed positive. You still need to check if (x2 - x1)/(v1 - v2) or just v1 > v2 is positive to print out "YES"

abhishek_cs + 0 comments @maximshen, why do we need to check this condition(x2-x1)/(v1-v2) if we initially find out that v2â‰§v1 and there is no solution. lets undarstad this with example: take minimum value of x1 i.e, x1=0 so we can take x2=1 because according to problem statement x2 is always greater than x1. now if v1 and v2 bothe are equal then x1 will never catch x2 because of same speed, in this case no solution and print "no". so we can proceed further for solution, only when v2 is less than v1, hence v1-v2 is always positive integer. so there is no need for cheking (x1-x2)/(v1-v2).

mokshjackson100 + 1 comment Where it is stated that x2>x1?

beastieric + 0 comments In the constraints.

panjama231 + 0 comments "The problem states that x2 is strictly greater than x1."

I see no evidence for this. I've read through the problem multiple times.

pratik9044536615 + 0 comments [deleted]Anuj009 + 0 comments Absolute value should take care of the negatives.

plmuon + 0 comments Yes there are a number of conditions to check:

int num = x2 - x1; int den = v1 - v2; if (den == 0) cout << "NO"; else if (num % den != 0) cout << "NO"; else if (num > 0 && den < 0) cout << "NO"; else cout << "YES";

If x1 < x2 would not be stated, there are just two more conditions to check:

if (num == 0) cout << "YES"; else if (den == 0) cout << "NO"; else if (num % den != 0) cout << "NO"; else if (num < 0 && den > 0) cout << "NO"; else if (num > 0 && den < 0) cout << "NO"; else cout << "YES";

TimSylvester + 6 comments Doesn't handle the case where 2 starts ahead and 1 never catches up (e.g., 0 2 5 3). You need to ensure that the sign of the position difference and the sign of the velocity difference are opposite, i.e., the velocity will overcome the position difference rather than increase it:

`print("YES" if (x2 - x1) * (v2 - v1) < 0 and (x2 - x1) % (v2 - v1) == 0 else "NO")`

This also short-circuits a divide-by-zero error if the velocity difference is zero (e.g., 43 2 70 2).

ShubhamRRathi + 2 comments What is the logic (physics) behind this (x2 - x1) * (v2 - v1) < 0 condition?

wasazimbo + 1 comment I do a precheck for the condition where the kanagaroos travel at the same speed but at different locations (i.e. if(x1 > x2 && v1 > v2) or if(x2 > x1 && v2 > v1)). Beyond that I'm having logic errors when it comes to testing their convergence point.

abhishek_cs + 0 comments according to the problem statement x1 will never be greater than x2 then why do we need to check (x1>x2).

abhi195 + 1 comment ->Product (x2-x1)*(v2-v1) would be >0 when one kangaroo starts ahead of another kangaroo and with greater velocity then another kangaroo. In that case another kangaroo will never be able to catch up.

->Product (x2-x1)*(v2-v1) would be =0 when,

1)Both start with same location but different speed.

2)Both start with different location but same speed.

in either case they will never meet.

eg. 0 5 3 10

(x2-x1)*(v2-v1)>0 First kangaroo will never be able to catch up.

So what we require is (x2-x1)*(v2-v1)<0.

poyrazus + 2 comments Check (v2 < v1) instead of (x2 - x1) * (v2 - v1) < 0 because (x2 - x1) is always greater than zero (given in constraints). Thus;

System.out.println((v2 < v1 && (x2 - x1) % (v2 - v1) == 0 ) ? "YES" : "NO");

lduran + 0 comments This is the best solution

shabeena18 + 0 comments good one!!

koneru_harsha499 + 3 comments can anyone explain the logic behind..... (x2-x1)%(v2-v1)==0

anonymous0169 + 1 comment solving the equation mentioned above, x1+ y*v1=x2+ y*v2 , we get (x1-x2)/(v2-v1)= y . Since y is number of jumps so it has to be an integer. thus (x2-x1)%(v2-v1)==0

maniksrr + 3 comments how (x1-x2)changed to (x2-x1)?

acm_liu11 + 0 comments I think that is a typo - Mily94's post clearly shows the equation there:

(x1 - x2) % (v2 - v1) == 0

But, you are also able to produce the same value in a different expression. This depends on how you manipulate your 2 functions

(x2 - x1) % (v1 - v2) == 0

adi_bhutani16 + 0 comments x1+y*v1 = x2+y*v2

=>(x1-x2)+y(v1-v2) = 0

=>(x1-x2) = -y(v1-v2) Removing the '-ve' sign from RHS =>(x2-x1) = y(v1-v2)

=>(x2-x1)/(v1-v2) = y ----(1)

If you multiply -1 to both the numerator and denominator, then

=>(x1-x2)/(v2-v1) = y ----(2)

Thus equation (1) and (2) are the same.

NanthithaShankar + 0 comments Because it is stated that X2 is always higher than X1 in the problem.

cosmosh + 0 comments remainder is non terminating , ex= value of pi

ashishgulati21 + 0 comments relative velocity concept...if time of seperation of approaching is zero then bothare at same location at a particular time

md_nurezaman + 2 comments What if x2=x1 and v2=v1 ??

koneru_harsha499 + 1 comment both will meet at first jump....so yes will be answer

md_nurezaman + 0 comments But not according to the logic given by @TimSylvester. Isn't it?

abhisheksn + 1 comment Violates the question condition of x2>x1

md_nurezaman + 0 comments Sorry didn't notice that. My bad

kushssj + 0 comments [deleted]abenkalv + 0 comments Can you please explain how did you do (x2 - x1) * (v2 - v1) < 0?

yoleg + 1 comment First you need to solve for y where there is no remainder as discussed above.

Then you need make sure the velocity is correct in that one of the kangaroos will eventually catch up to the other kangaroo.

// javascript solution var remainder = (x1 - x2) % (v2 - v1) == 0; var properVelocity = ((x1-x2 > 0) && v2 > v1) || ((x1-x2 < 0) && v1 > v2); return remainder && properVelocity ? 'YES': 'NO';

twknab + 1 comment This is a really great solution -- thanks for sharing this -- nice and clean!

yashpatel7025 + 0 comments thanks twknab

Khushboo_Watwani + 1 comment can you please explain, how the value of "y" is calculated...

wasazimbo + 1 comment I found y didn't really need to be calculated if using a loop that performs the x1+v1 and x2+v2 calculation at the same time. That way you can do a simple check at the beginning of each calculation to see if their positions are equal

pc_leo + 0 comments I am using the same method but what should be the condition of the loop? some of my test cases are failing...

thaihocmap123 + 0 comments it is too perfect !!!!

ManoRanjithK + 0 comments Simpler than my algo..Thanks for sharing.. Thumbs Up !!

srachel27 + 0 comments on theory if (x1 - x2) % (v2 - v1) == 0 is good, if v2-v1 equal to one will fail, and if condition is if (v1 == v2 && x1 != x2) or (x2 > x1 && v2 > v1) or (x1 > x2 && v1 > v2) then don't need waste time calculate it, the answer will be no

rajatcube + 1 comment Hello umm i solved it in a different way using arrays but it was way more tedious than this mod(%) thing. I just checked it out and it works much much much better than mine. Its just that how did u get to that thing. I mean did u read any formulae or anything coz i really wanna get this. Just a little background i have been coding since 2 months(I am a first year student and have learnt java in my school and thats all) and I am practicing after one whole year . So i would be grateful if someone really guide me on this. Thanks in advance :)

beastieric + 0 comments If the two kangaroos met, then there woulde be an integer n such that x1 + n * v1 = x2 + n * v2. Subtracting x1 from both sides, we get that n * v1 = x2 - x1 + n * v2. Then we subtract n * v2 from both sides and we get n * v1 - n * v2 = x2 - x1. Factoring out n from the left side of the equation, n * (v1 - v2) = (x2 - x1). We can the divide both sides by (v1 - v2) and we get (x2 - x1) / (v1 - v2). If this is an integer, then (x2 - x1) % (v1 - v2) has to equal 0.

anonymous0169 + 0 comments [deleted]dredd + 0 comments wrong for given case( 0 2 5 3) and many others....

mssrivathsan + 1 comment The condition should be (V2 < V1) && (X2 - X1) % (V1 - V2) == 0 :)

sgaweda + 0 comments I knew something was missing and it took me until here in the comments to actually understand what it was.

Meenachinmay + 0 comments not true,,,,,,,

lalitha1729 + 0 comments in second case :0 2 5 3 in this case x1=0,x2=5,v1=2,v2=3 so (x1 - x2) % (v2 - v1) == 0 as -5%1==0, so this is not correct

wangfuqing80 + 0 comments Yes we just need a couple of check cases to deal with negatives and zeros

kiamottullah + 1 comment why y is same for two jumps ? why not y1 y2 ?

dev_dibyo + 0 comments Because if one kangaroo takes a jump , the other one would have also taken as both jump at same time . So number of jumps for a paticular period of time remains the same . Hence , y is same for both cases .

SmartJavaGeek + 1 comment What if (v2-v1) == 1? For example, if x1=0, v1 =3 , x2 = 100 and v2= 4, will each other meet?

beastieric + 0 comments No, because the 2nd kangaroo started ahead of the 1st one and will keep getting more ahead. However, this is not because v2 - v1 = 1. This is because x1 - x2 is negative while v2 - v1 is not, so it would take negative steps to get there, which can't happen.

jacob0306 + 0 comments 112 9563 8625 244 this is one of the test case and according to your logic the answer will be NO instead of YES which is the right answer!

Sojanya + 1 comment Can you provide the name of the equation which you applied and solved? How can I learn about this... Please any link from wikipedia or any other website if possible.

jacob0306 + 0 comments 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) System.out.println("NO"); else if (((x1 - x2) % (v2 - v1)) == 0 && ((x1 - x2) / (v2 - v1)) > 0) { System.out.println("YES"); } else System.out.println("NO"); }`

Let me explain how I do it. Let y1 be the total amounts of jumps that kangaroo 1 does so we have:

x1 + y1*v1 = S1, the distance that kangoroo 1 will get to after jumping y1 times.

Similarly, x2 + y2*v2 = S2, the distance that kangoroo 2 will get to after jumping y2 times.

Question: Given the starting locations and movement rates for each kangaroo, can you determine if they'll ever land at the same location at the same time?

so it means they will meet when S1 = S2 => x1 + y1*v1 = x2 + y2*v2, now we assume that both kangaroo did the same jump then met each other at the same location so the equation now is

x1 + y*v1 = x2 + y*v2 <=> y = (x1 - x2)/(v2 - v1) now can you guess what is the condtion for y is base on the above equation?

that is how I understand it but I may be wrong and sorry for my bad explaination, English is not my first lanquage.

jessibird + 1 comment Using this algorithm and additional tweaks, here is the python 2 code:

if v2 > v1 and x2 > x1: print "NO" elif x1 > x2 and v1>v2: print "NO" elif x1 != x2 and v1 == v2: print "NO" elif (x1-x2)%(v2-v1) == 0: print "YES" else: print "NO"

shivammutreja25 + 2 comments Hey Python buddy! You don't need to check whether x2>x1, it's already given in the constraints.

This should work. Cheers!

if v1 > v2 and (x2-x1)%(v1-v2) == 0: print "YES else: print "NO"

[deleted] + 0 comments This code reurns an error, when v1 = v2 => v1 - v2 = 0.

Ardillo + 0 comments Or this complete solution:

x1, v1, x2, v2 = list(map(int, input().split())) x, y = sorted([[x1, v1], [x2, v2]], key=lambda el: el[0]) if not x[1] > y[1] or (x[0]-y[0]) % (x[1]-y[1]): print('NO') else: print('YES')

supunrajasinghe + 1 comment how can you solve these equation? please can you explain it.

alison_thaung + 1 comment Let n = number of times each kangaroo hops to eventually land at the same exact distance. To see whether that does happen we need the following expression to be true:

x1 + (v1 * n) = x2 + (v2 * n)

We can check this by looking at the sample input 0, 3, 5, 2 for x1, v1, x2, v2 respectively.

0 + 3n = 5 + 2n n = 5

This means it takes the kangaroos jumping 5 times to land at the same distance:

0 > 3 > 6 > 9 > 12 > 15

5 > 7 > 9 > 11 > 13 > 15

Now that we know the equation is right, let's move n to one side:

(v1 * n) - (v2 * n) = x2 - x1

n(v1 - v2) = x2 - x1

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

We don't know what the value of n will be, but we know that it must be an integer. If the division solves for a whole integer, we know there is no remainder value. So, we use modular division

(x2 - x1) % (v1 - v2) == 0 (meaning no remainder value, and therefore the division solves for an integer)

joseph_mawer + 2 comments How did you know to use the expression x1 + (v1 * n) = x2 + (v2 * n)?? What area of math is this from? What is the name of this expression?

Zarif123 + 0 comments These are linear equations, you usually see them as y=mx+b. Here x1 is b and v1 is m.

hacker_y4s853t8 + 0 comments The equation is an equality to find if there is some value n (number of jumps) such that:

x1 + (v1 * n) = x2 + (v2 * n)

Or in english:

Is there a number N such that

Kangaroo one's position + (it's velocity * N) == Kangaroo two's position + (it's velocity * N)

Where N = the number of jumps

deadfire19 + 1 comment Java8 1 line:

int b = in.nextInt(); int a = in.nextInt(); int d = in.nextInt(); int c = in.nextInt(); System.out.println( b == d || (a-c) != 0 && (((d-b) / (a-c))*a)+b > Math.max(b, d) && ((b-d) % (a-c)) == 0 ? "YES" : "NO" );

Ardillo + 0 comments 1 line?

4 lines for input reading and the lenght of the println is higher than the maximun allowed by the standards so this final line needs to be splitted into two.

4 + 2 is 6 lines not 1.

shad0w99 + 1 comment But do the nummber of jumps need to be the same for both the Kangaroos? I feel that x1+a*v1=x2+b*v2 relates more closely to the problem. Thoughts?

DearVolt + 0 comments I agree - It would be a cooler question. The question does have this note though:

"Note: The two kangaroos must land at the same location after making the same number of jumps."

vikihacksys + 0 comments but what is the limit of y? how to identify the limit of jumps from the given problem?

SreeHarsha_K + 0 comments 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(); int a = x1 - x2; int b = v1 - v2; String res = "NO"; if(a*b < 0 && a%b == 0){ res = "YES"; } System.out.println(res); }

mhlaskar1991 + 0 comments Please explain a bit more.

prashant_pal1212 + 0 comments i think this will help....

# include

# include

using namespace std;

int main(){ int x1; int v1; int x2; int v2; cin >> x1 >> v1 >> x2 >> v2; if((x1>x2&&v1v2)){ double remainder; remainder = abs(x1-x2)%abs(v2-v1); if (remainder==0.0){ cout<<"YES"; return 0; }

`} cout<<"NO"; return 0;`

}

WittyNotes + 0 comments Yup. Producing a solution like this...

int num = x1 - x2; int den = v2 - v1; System.out.println((den == 0 || num % den != 0 || num/den < 0) ? "NO":"YES");

prakhar_mishra + 0 comments Yup. cracked that !

paridhi_pk7 + 1 comment The case test 10 is giving a runtime error, else if quite fine, tried different codes... even 'v1 = x2 + y * v2 where "y" is number of jumps... so if (x1 - x2) % (v2 - v1) == 0 ' this

DearVolt + 0 comments You need to watch out for when v1 == v2 because then you will try modulus of 0. In this case or the more general case where v2 >= v1, the answer is always NO because the kangaroo just can't catch up.

codebloode_123 + 0 comments good one man

[deleted] + 0 comments Your idea helped me solve this. Thank You! :D

rhpkp + 0 comments really amazing

S_K_Sharma + 0 comments [deleted]jacomatic + 0 comments excellent! this really helped.

styopdev + 0 comments [deleted]aurora19 + 0 comments woahh thank you! i spent so long on this question

defields923 + 0 comments My first attempt was to brute force it with a loop, but JS will timeout. I came to a similar conclusion to fix it, though one or two steps less elegant. Nice deduction!

ScienceD + 0 comments What do you guys thing about this? This idea came to me on my own lol!

#include <iostream> using namespace std; /*Kangaroo functions: Kangaroo 1 = v1 * n + c1 Kangaroo 2 = v2 * n + c2 No matter how different c is, kangaroo with biggest speed will always catch up also v*n is more important than c cos v*n has higher degree P.S. I forgot about NOTE ._.*/ int main() { int c1, v1, c2, v2; cin >> c1 >> v1 >> c2 >> v2; // below: division by 0 is bad! int meet_step = v1-v2 != 0 ? (0 - (c1 - c2))/(v1 - v2) : 0; int meet_mod = v1-v2 != 0 ? (0 - (c1 - c2))%(v1 - v2) : 1; if(meet_step > 0 && meet_mod == 0) cout << "YES";// only if step where our kangaroos else // meet is positive AND is an integer, they meet cout << "NO"; //on the ground, not in the air return 0; }

alcides_ticlla + 1 comment this fails for this case

0 3 4 2

the equation states that the kanguru will never match the same point but output is stating that it should collide

for 1: 0 3 6 9

for 2: 4 6

so they will jump for the same x but never at the same time seems like a bug on the problem definition

Zinuxs_Torvalds + 0 comments The iteration is infinite and btw it meets at 12.

padalkars + 0 comments Great!!!. So simple. Thanks.

ben_nxumalo + 0 comments PHP version that worked for me if((v1 && x2)||(x2 && v2)) return "NO"; elseif(x2 || v2) return "NO"; elseif((x2) % (v1) == 0) return "YES"; return "NO";

minLewis + 0 comments Ah so if the difference in origin is divisible by the difference in velocity, then at some point they will meet. Awesome. Had to sketch that one out

bhatushar + 2 comments The condition is working but I don't understand the principle behind the

*(x1 - x2) % (v2 - v1) == 0*equation. Can anyone help me?beastieric + 0 comments If the two kangaroos met, then there woulde be an integer n such that x1 + n * v1 = x2 + n * v2. Subtracting x1 from both sides, we get that n * v1 = x2 - x1 + n * v2. Then we subtract n * v2 from both sides and we get n * v1 - n * v2 = x2 - x1. Factoring out n from the left side of the equation, n * (v1 - v2) = (x2 - x1). We can the divide both sides by (v1 - v2) and we get (x2 - x1) / (v1 - v2). If this is an integer, then (x2 - x1) % (v1 - v2) has to equal 0.

DearVolt + 0 comments There's a really nice explanation here: https://www.hackerrank.com/challenges/kangaroo/forum/comments/327371

Codone + 0 comments Actually that didn't strike :-)

krauszrobert92 + 0 comments return v2<v1 && !((x2-x1) % (v2-v1)) ? "YES" : "NO";Blaze_Hacker + 0 comments Awesome

alihashir4799 + 1 comment "(x1 - x2) % (v2 - v1) == 0" ??. Can you please explain this??

santhosh10dm43 + 0 comments how these maths logics are finding not a good student in maths lol.

HCLarsen + 0 comments I had to add in a line of "return "NO" if v2 == v1" to avoid runtime divide by 0 errors, but other than that, this worked great.

joseph_mawer + 1 comment What equation is this? How did you know to use that equation? Thanks!

sanjay311999 + 0 comments The problem asks whether they will meet at a particular point after same number of jumps. Distance moved after 'y' jumps kangaroo1 d1 = x1 + v1 * y. kangaroo2 d2 = x2 + v2 * y. 'y' must be same for both kangaroos. d1 = d2. x1 + v1 * y = x2 + v2 * y. rearanging the above equation we get y = (x2 - x1)/(v1 - v2). y is number of jumps which must be a positive integer. Therefore which implies that x2-x1 is divisible by v1-v2. This is how the equation has evolved.

deepnath01 + 0 comments [deleted]HimanshuMakhija + 0 comments Nice way to think about it

dhanasing17 + 0 comments can you explain how x1 + y * v1 = x2 + y * v2 is converted into (x1 - x2) % (v2 - v1) == 0

santoshimn1 + 0 comments Wow thatz really brilliant logic!!!

r141938 + 0 comments by this formula i got wrong result

fanjavaid + 0 comments How you can define using this formula? x1 + y * v1 Why x1 must be add by y and multiply by v1?

Thank you

hani_merzouki + 0 comments that a good aproach that i have tried but the problem is that it does not have the notion of time. the problem says that the kangoroos meet at the same time (or after the same number of jumps) and not just meet. im still working on that part if anyone has any ideas :)

ashishgupta2598 + 0 comments Its like Arithmatic Progression. Like we have to find where two Ap meet But please also justify How u take the number of jumps equal?? Take case as 2,6,8..... and 0,3,6,9.....

ashishgupta2598 + 0 comments Also Take the case when number of jumps are not equal

tecnocratay + 0 comments thank you...you just made it easy!

leeoim + 0 comments How did mathematically solve x1 + y * v1 = x2 + y * v2 to (x1-x2)%(v2-v1) == 0?

qvanphong + 0 comments static String kangaroo(int x1, int v1, int x2, int v2) { for(int i = 1; i > 0; i++){ if(x1+i*v1 == x2+i*v2){ return "YES"; }else if(x1+i*v1 > x2+i*v2) { return "NO"; } } return null; }

This will perform infinite loops until kangarooA > kangarooB, the result will be NO. Cuz at the beginning, kangarooA's starting location always less than kangarooB's location. Else, if kangarooA equals kangarooB (as Mily94 formula), the result we be YES. But this isn't optimal code, it take over 1s to show result from execution.

sha3gatto + 0 comments [deleted]joseph_zamora64 + 0 comments `bool diff; string out = "NO"; for(int x = 0; x < MAX; x++){ diff = ((v1*x+x1)-(v2*x+x2)) == 0; //cout << ((v1*x+x1)-(v2*x+x2)) << endl; if(diff){ out = "YES"; break; } } return out; here is another way to do it, MAX is 10000 since it will never go above that.`

sha_coder + 0 comments [deleted]kerak19 + 0 comments [deleted]beckamjunior7 + 0 comments [deleted]tjorgais0021 + 0 comments [deleted]ibrahimhadzic45 + 0 comments `def kangaroo(x1, v1, x2, v2): if (v2 >= v1 or (x2-x1)%(v1-v2) != 0): return 'NO' return 'YES'`

We first check if v2 (second kangaroo's jump) is bigger or equal to v1 (first kangaroo's jump) because there's a constraint that x2 (starting position of the second kangaroo) has to be bigger than x1 (starting position of the first kangaroo). It means that for first kangaroo to reach the second one it has to have bigger jump than the second kangaroo. If the second kangaroo has bigger or equal jump, the first will never catch it, therefore the statement is satisfied and we return a 'NO'.

If the first condition is not satisfied, we check if the combination of starting positions and steps makes it impossible for the first kangaroo to reach the second. If it indeed is impossible (if its modulus doesn't equal zero) we again return a 'NO'.

If none of these happen, we return a 'YES'.

generalom1234 + 0 comments I could only think of this bit but thanks for helping brothah... Appreciate it...

if((x2+v2)%v1 == 0) cout<<"YES";

tmcleod07 + 2 comments Not quite. If y is negative your solution can fail, depending on how the '%' is implemented.

generalom1234 + 0 comments but in my case y won't be -ve will it? but in the statement (x2-x1)%(v1-v2) == 0,x2 - x1 and v1-v2 will always be +ve if we r considering the YES statement

generalom1234 + 1 comment basically i can't understand what u r trying to imply here can u be more specific?

tmcleod07 + 1 comment @generalom1234, I was reponding to the original (parent) post. In the original post, if you convert the expressions to floating point and solve for 'y', The kangaroos meet if y is a non-negative integer, otherwise they do not meet.

generalom1234 + 0 comments ohkkk

valentin_lafran1 + 0 comments Hi, I think your equation is wrong ... Actually you take "y" number of jump as a common factor for both kangaroos, but number of jumps will be different for kangaroo1 and kangaroo2 so we should have y1, y2 number of jump for each kangaroo, am I right ?

mrgnwatson + 10 comments I think the formula is messing people up on this. I have found that using words, rather than variable names, to be helpful when writing out the problem.

So we have two kangaroos starting at different locations, and jumping forward at different distances. If we want to know where any kangaroo is at any given time, there is an intuitive equation for that:

Kangaroo Position = (Number of Jumps * Distance per Jump) + Starting Position.

We could also write this as:

K = yv + x

such that K =

**Kangaroo Position**, y =**Number of Jumps**, v =**Distance Per Jump**, and x =**Starting Position**.That almost looks like an equation your teacher went over in algebra that one time you were dozing off:

`y = mx + b`

. I know we are talking about kangaroos here, but in the background we are really just checking to see when two lines intersect.If we have two kangaroos and we want to know when (or if) they will intersect, given their

**Starting Position**and**Distance per Jump**, the only thing left to solve for is**Number of Jumps**.The kangaroos crossing paths essentially means that

**Kangaroo Position**is equal for both kangaroos. Remember the equation up above`K = yv + x`

? Now that we have two kangaroos, we need to have 2 different equations, and need to determine which value of y (**Number of Jumps**) can be plugged in to make them equal. So now we have something like this:(y * v1) + x1 = (y * v2) + x2

We need to get

`y`

on one side of the equation, so we will begin reducing it down.(x1 - x2) = (y * v2) - (y * v1)

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

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

Luckily, the problem statement gives us the

**Starting Position**and**Distance per Jump**(`x1`

,`x2`

,`v1`

, and`v2`

) for each kangaroo. When we plug in these numbers it will tell us how many jumps it would take for the kangaroos to end up in the same spot. But not so fast! We can do a a little work up front to check if the kangaroo that is starting in front is moving faster than the kangaroo in the rear i.e we need to see if**Distance Per Jump**for the kangaroo in front is larger than the one in the rear. If so, then the one in the back will never catch up. Before we even attempt find an intersection we need to ensure that`v2 < v1`

is`true`

. If this evalutes to`false`

then we are done and the lines will not intersect at any point in the future. If the kangaroos started going the other direction then that would be a different story.Anyway, so we plugged the numbers in and we are ready to see how many jumps it will take. At this point there are two scenarios that will occur:

- you got a whole number greater than zero
- you got a fractional number greater than zero

In scenario one, this means that after

`y`

jumps, the kangaroos will be in the same spot.In scenario two, the kangaroos will intersect, but they will be in the air. Kinda cool, but not what we wanted.

Now we get to the part that seems to mess with peoples heads: the dreaded

`%`

operator. Keep reading, and you will see the solution to this problem.# SPOILER ALERT

The code below is how we validate that the point of intersection is a whole number.

(x1 - x2) % (v2 - v1) == 0

The

`%`

operator returns the remainder of dividing two numbers. Lets look at an example:x1 = 0 x2 = 4 v1 = 3 v2 = 2 (0 - 4) / (2 - 3) => (-4 / -1) => 4 = y

There is no remainder here. So

`(-4 % -1) == 0`

and the kangaroos will intersect after 4 jumps.So to put it all together, we need to check the

**Distance per Jump**of the kangaroo in front is less than the one in the rear, and that the equation above gives us a positive integer.String response = "NO"; boolean canCatchUp = (v2 < v1); if(canCatchUp) { boolean willIntersectOnLand = (x1 - x2) % (v2 - v1) == 0; if(willIntersectOnLand) { response = "YES"; } } System.out.println(response);

arguewithplato + 0 comments This is a great writeup, thank you!

jessiepusateri + 0 comments Really great explanantion! Thanks!

rafaele + 0 comments That's a very clear & helpful explanation. Thank you.

gmzdev1986 + 0 comments clever

mathankumar26 + 0 comments very good explanation.Thank you :)

NickWoodward + 1 comment this has got no where near enough love.

where can I get better at recognising these sorts of patterns? or is it just a matter of knowing that when something intersects you have to use y = mx + b ?

eitherway, nice one! (I just cheated:)

if(x1 < x2 && v1 < v2) return "NO"; while(x1 <= x2){ x1 += v1; x2 += v2; if(x1 == x2)return "YES"; } return "NO";

stolenunder1 + 0 comments Intersection is not always in the form of y = mx + b, this is a linear equation involving one variable (the x, or in our case the number of jumps). We could also have a linear equation with 2 variables, we could also have a mixture of linear and non-linear equations (such as an exponential equation and a linear equation and finding their point of intersection).

Honestly the only shorcut is improving upon math, otherwise you'll be limited by trying to remember certain solutions to equations and when to apply them, but you'll rarely know when NOT to apply them, or which ones to apply for a problem that's a bit more complex :(

A bit more explanation for this one, the Kangaroos jump at a linear rate (their veolcity/jump movement never changes, it's always v1 or v2). Therefore we have something along the lines of:

y = velocity * jumps + startLocation

We are already given velocity AND start location for each kangaroo. let's abbreviate using the actual equation variables (x1,x2,v1,v2), we get two separate equations for y (the total distance travelled after J jumps)

- y = v1 * J + x1
- y = v2 * J + x2

We want to set these equal to each other, this would give us a distance that they both share when their J variable's are equal to one another:

v1 * J + x1 = v2 * J + x2

And using our algebra we get the EQ described above in the other posters solution:

v1 * J - v2 * J + x1 - x2 = 0 Which can be written as: J(v1-v2) = x2 - x1 or (x2-x1) / (v1-v2) = J

So given 2 velocity values and 2 starting positions, like 4 = v1 and 2 = v2 and 0 = x1 and 4 = x2, we can evaluate:

- (4 - 0) / (4-2) = J
- 4 / 2 = J
- J = 2 (so at 2 jumps we should intersect)

Showing the values below of the jumps this is right (the far left value is the starting, arrows point to the next jump location):

- 0 -> 4 -> 8
- 4 -> 6 -> 8

And then of course, as the above states, we need to make sure the jump total is a whole number, otherwise we're intersecting in the air. Which is fine, but this problem doesn't really allow that. After all, given any 2 kangaroos if the "BACK" kangaroo is moving FASTER than the one in front of it, they will eventually collide. It's like 2 cars and the one in back is moving faster, if it doesn't slow down it will hit the one in front of it!

pbase + 0 comments Fabulous write-up. Thanks!

tatianaensslin + 0 comments wooohooo needed this thank ya!

mike232 + 0 comments This is a brilliant write up, thanks for this.

borao + 0 comments Thank you!

nasimoyz + 6 comments **Explaining**`(x2 - x1) % (v1 - v2) == 0`

On the default example

`0 3 4 2`

I began by picturing K2 was ahead**but not moving**.k1 - - - k2 x=0 x=4 v=3 v=0

Now we just have to see if K1 will land on

`4`

as it hops by.This is a simple matter of whether

`v1`

is a factor of`4`

(clearly it will jump over it):(x2 - x1) % v1 = (4-0) % 3 = 1

Imagine the alternative case where

`K2`

is also moving:`v2 = 2`

If

`v1 > v2`

we know`v1`

will eventually catch up. If on each jump K1 advances 3 steps and K2 advances 2 steps, then K1 is gaining on K2 by`3 - 2 = 1`

each jump (each jump they'll be 1 less apart than the jump before). Now K1 just has to close that original distance (`4`

).4 6 8 10 12 <- K2 0 3 6 9 12 <- K1 4 3 2 1 0 <- Difference 1 1 1 1 <- Rate

If the

`rate at which the distance is closing`

can add up to the original distance between them (`4`

), you know they'll eventually meet.Now take the example

`3 4 10 2`

where they do not meet.10 12 14 16 18 <- K2 3 7 11 15 19 <- K1 7 5 3 1 -1 <- Difference 2 2 2 2 <- Rate

The rate isn't a factor of the original distance, therefore they will never meet:

`7 % 2 = 1`

shahane_rohan96 + 0 comments Very good explanation indeed! It is far better to post logic behind the code that to post code itself! Thank you!

zambro + 0 comments Thank you for that detailed explanation :)

jacob0306 + 0 comments 112 9563 8625 244 how about this test case? the right answer is yes but i dont know how to get to that answer

supunrajasinghe + 0 comments thankx man.

aaronshaverpdx + 0 comments Great explanation, THANK YOU

kerak19 + 0 comments [deleted]

james_tanner + 2 comments This problem can be solved purely mathematically, without any iteration.

Assume that there exists some k number of jumps, at which they will meet:

`x1 + k(v1) = x2 + k(v2)`

Solving for k:

`k = (x2 - x1) / (v1 - v2)`

If k would be a positive integer, they will land at the same location in k jumps.

(Note: If k is negative, they would have to hop backwards. If k is not an integer, they will pass eachother while in the air.)

So you just need to evaluate if that function would result in a positive integer. You don't even need to actually determine a value for k. And no iteration is required.

The code for this is left as an exercise for the reader.

nimon + 0 comments Well, determining whether is integer probably requires some variation of the Euclidean algorithm in your chosen language's implementation of the remainder (or quotient) operator. Some iteration is needed, we just don't need to write it.

bhaskar1126 + 0 comments u are genius teacher

RodneyShag + 1 comment ### Java solution - passes 100% of test cases

From my HackerRank solutions.

**Case 1:**v1 <= v2. In this case, kangaroo 1 can never catch up to kangaroo 2

**Case2 :**x2 - x1 represents the distance between the 2 kangaroos

v2 - v1 represents the difference in velocities between the 2 kangaroos. It also represents how much closer the kangaroos get in each step (until they either meet or 1 kangaroo passes the other)

If the distance between the kangaroos (x2 - x1) is divisible by how much closer they get in each step (v2 - v1), then they will land at the same location at the same time. Otherwise, 1 kangaroo will jump over the other and they will never be at the same location at the same time.

import java.util.Scanner; public class Solution { public static void main(String[] args) { /* Read and save input */ Scanner scan = new Scanner(System.in); int x1 = scan.nextInt(); int v1 = scan.nextInt(); int x2 = scan.nextInt(); int v2 = scan.nextInt(); scan.close(); /* See if kangaroos meet each other */ if (v1 <= v2) { System.out.println("NO"); } else { boolean kangaroosMeet = (x2 - x1) % (v2 - v1) == 0; System.out.println(kangaroosMeet ? "YES" : "NO"); } } }

Let me know if you have any questions.

hemankur + 1 comment Can you please explain why we used (x2 - x1) % (v2 - v1) == 0

RodneyShag + 1 comment Hi. I just added an explanation to my original post to help answer your question.

jgl359 + 0 comments [deleted]

marinskiy + 0 comments Here is

**Python 3**solution from my HackerrankPractice repository:def kangaroo(x1, v1, x2, v2): return 'YES' if (v1 > v2) and (x2 - x1) % (v2 - v1) == 0 else 'NO' x1, v1, x2, v2 = map(int, input().split()) print(kangaroo(x1, v1, x2, v2))

Feel free to ask if you have any questions :)

mikelane + 1 comment My python:

#!/bin/python3 import sys x1,v1,x2,v2 = input().strip().split(' ') x1,v1,x2,v2 = [int(x1),int(v1),int(x2),int(v2)] if x1 == x2: print('YES') try: quotient, remainder = divmod(x2-x1, v1-v2) except ZeroDivisionError: print('NO') else: if quotient > 0 and remainder == 0: print('YES') else: print('NO')

SamRwanda + 0 comments From the constraints,

*x1 < x2*soif x1 == x2: print('YES')

is redudant.

saurabhvijay17 + 3 comments `Below is my code , all the test cases are successful except TestCase 10 which gives RunTime Error. I checked the TestCase 10 (112 9563 8625 244 ) manually and it is getting excuted with correct answer.`

int a, b; if(v1<v2){ System.out.println("NO"); } else{ a = x2 -x1; b = v1-v2; if(a%b == 0){ System.out.println("YES"); } else{ System.out.println("NO"); } }

markus_alpers + 1 comment Same problem with me, though this would be my main()-Method (Java)... and by now I found the mistake due to another post. (Damn it's one of those really simple mistakes.):

`Scanner scan = new Scanner(System.in); int x1, x2, x, v1, v2, v; long n; String result = "NO"; x1 = scan.nextInt(); v1 = scan.nextInt(); x2 = scan.nextInt(); v2 = scan.nextInt(); x = x1 - x2; v = v2 - v1; n = x / v; if ((n > 0) && (n * v == x)){ result = "YES"; } System.out.println(result);`

stshprsdmshr + 1 comment still test case 10 is wrong.I can't identify what's wrong!!

Palmen + 1 comment Hey, I had the same problem (RunTimeError, IlligalArgument Exception (division by zero)). Check if v2-v1 is different from 0. That was the problem in my case.

karuppiahit + 0 comments add this condition under try-catch and print "NO" as a catch handler. Because in case 10 we have a DBZ exception.

Cheers. Happy Coding...

crazypan + 2 comments while((x1+=v1)<(x2+=v2)); System.out.print((x1==x2)?"YES":"NO");

sharifcse57 + 1 comment Here if position of second item is greater then position of first item then we will check, the valucity of first item is greater or not. If valucity is greater of first item only it can be possible to meet them together .

if(x2>x1 && v1 > v2 && ((x1-x2)%(v1-v2) == 0)) { return "YES"; } else{ return "NO"; }

crazypan + 0 comments It's mentioned in the problem statement. 0 <=x1 <= x2 <=10000

fadi114 + 0 comments

Sort 1125 Discussions, By:

Please Login in order to post a comment