Given two kangaroos on a number line ready to jump in the positive direction, we 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.
Read full problem statement from here
Working solution in Swift
func kangaroo(x1: Int, v1: Int, x2: Int, v2: Int) -> String {
var multiplier = 1
// 1.
while(multiplier < 10000) {
// 2.
if (x1+(v1*multiplier) == x2+(v2*multiplier)) {
return "YES"
}
multiplier += 1
}
return "NO"
}
kangaroo(x1: 0, v1: 2, x2: 5, v2: 3) // prints "NO"
Explanation
- Repeat the multiplier (as each jump attempts) until the given constraint max 10000 times.
- Try to match distance travelled on each jump attempts. If so, return 'YES'.
Have you found better solution? Found this article useful ? Let us know in the comments. Thanks for reading.