Skip to content

Instantly share code, notes, and snippets.

@M15t
Created April 4, 2024 14:37
Show Gist options
  • Save M15t/616e40a0c3ee4957ccad6ddd477d817c to your computer and use it in GitHub Desktop.
Save M15t/616e40a0c3ee4957ccad6ddd477d817c to your computer and use it in GitHub Desktop.
Non-empty array
import java.util.HashSet;
class Solution {
public int solution(int[] A) {
int currentPosition = 0;
int jumps = 0;
HashSet<Integer> visited = new HashSet<>();
while (currentPosition >= 0 && currentPosition < A.length) {
if (visited.contains(currentPosition)) {
return -1; // Pawn entered a cycle
}
visited.add(currentPosition);
currentPosition += A[currentPosition];
jumps++;
}
return jumps;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment