Categories
interview

Frog Jump – Java

This solution uses a HashMap

class Solution {
 public boolean canCross(int[] stones) {
  int len = stones.length;
  HashMap < Integer, HashSet < Integer >> stoneToStep = new HashMap < Integer, HashSet < Integer >> ();
  for (int pos = 0; pos < len; pos++)
   stoneToStep.put(stones[pos], new HashSet < Integer > ());
  stoneToStep.get(0).add(1);
  for (int position = 0; position < len - 1; position++) {
   int stone = stones[position];
   for (int step: stoneToStep.get(stone)) {
    int reach = stone + step;
    if (reach == stones[len - 1])
     return true;
    if (stoneToStep.get(reach) != null) {
     stoneToStep.get(reach).add(step);
     stoneToStep.get(reach).add(step + 1);
     if (step > 1)
      stoneToStep.get(reach).add(step - 1);
    }
   }

  }
  return false;
 }
}

Alternate solution can use DFS (Depth First Search)