Circular Jump Game

Hard
0/120
0 upvote

Problem statement

A group of N people are seated in chairs numbered 1 to N arranged in a circle. You are given an array A, where A[i-1] represents the jump distance for the person on chair i.


From any chair i, a person can jump A[i-1] chairs in either a clockwise (right) or counter-clockwise (left) direction.


Bob starts at chair X and needs to reach chair Y. Your task is to find the minimum number of jumps required to get from chair X to chair Y. If it's impossible to reach chair Y, return -1.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains an integer, N, the number of chairs.

The second line contains an integer, X, Bob's starting chair.

The third line contains an integer, Y, the destination chair.

The next line contains N space-separated integers, representing the jump distances A[0] to A[N-1].


Output Format:
Print a single integer representing the minimum number of jumps.

If the destination is unreachable, print -1.


Note:
This problem can be modeled as finding the shortest path in an unweighted graph. The chairs are the vertices (nodes) of the graph, and the possible jumps are the edges.

Since all jumps have a "cost" of 1, a Breadth-First Search (BFS) is the ideal algorithm to find the shortest path.

The problem uses 1-based indexing for chairs X and Y. It's often easier to convert these to 0-based indices for calculations (e.g., start_node = X - 1).
Sample Input 1:
5
1
4
2 3 1 1 2


Sample Output 1:
2


Explanation for Sample 1:
- Start at chair 1. The jump distance is `A[0]=2`. Possible jumps are to chair 3 (1+2) or chair 4 (1-2 -> wrap around to 4). Let's trace one path.
A valid path is: `Chair 1 -> Chair 3 -> Chair 4`.
- Jump 1: From Chair 1, jump right by `A[0]=2`. Land on Chair 3.
- Jump 2: From Chair 3, jump right by `A[2]=1`. Land on Chair 4.
This takes 2 jumps. BFS would explore all paths of length 1 before exploring paths of length 2, guaranteeing this is the minimum.


Sample Input 2:
4
1
4
2 2 2 2


Sample Output 2:
-1


Explanation for Sample 2:
- From chair 1, you can only jump to chair 3 (1+2=3) or chair 3 (1-2 -> wraps to 3).
- From chair 3, you can only jump to chair 1 (3+2 -> wraps to 1) or chair 1 (3-2=1).
You are stuck in a loop between chairs 1 and 3. It is impossible to reach chairs 2 or 4.


Expected Time Complexity:
The expected time complexity is O(N).


Constraints:
2 <= N <= 10^5
1 <= X, Y <= N
1 <= A[i] <= N

Time limit: 1 sec
Approaches (1)
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Circular Jump Game
Full screen
Console