Created
April 4, 2024 14:37
-
-
Save M15t/616e40a0c3ee4957ccad6ddd477d817c to your computer and use it in GitHub Desktop.
Non-empty array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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