Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Can you reach the last index if a[i] is the maximum jump from i?

Problem: Can you reach the last index if a[i] is the maximum jump from i?
static boolean canReach(int[] a) {
    int far = 0;
    for (int i = 0; i < a.length; i++) {
        if (i > far) return false;
        far = Math.max(far, i + a[i]);
    }
    return true;
}
// canReach({3, 2, 1, 0, 4}) + " " + canReach({2, 0, 0}) + " " + canReach({0, 1})
What does the commented expression evaluate to?
  1. A. false true true
  2. B. false true false
  3. C. true true false
  4. D. false false false

Correct answer: B. false true false

Track the farthest index reachable so far; if i passes it, i is unreachable. In {3,2,1,0,4} every path lands on index 3 (value 0) and far stays 3. {2,0,0} reaches index 2 directly. {0,1} is stuck at 0. O(n).

More Coding Interview Problems questions

Exams that ask this topic