Optimizing a while loop in Java

Your code is pretty fast (O(n)), but this problem can be solved in constant time (O(1)), since it is just based on the condition of the intersection of two lines being an integer.

static String kangaroo(int k1, int v1, int k2, int v2) {
    float x = (k2 - k1)/(v1 - v2);
    if(x == (int) x) { //check if the intersection point is an integer
        return "YES";
    }
    return "NO";
}

Leave a Comment