forked from sambit77/Algoexpert-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleCycleCheck.java
More file actions
42 lines (39 loc) · 869 Bytes
/
SingleCycleCheck.java
File metadata and controls
42 lines (39 loc) · 869 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//Time Complexity O(n) | Space Complexity O(1)
import java.util.*;
class A
{
public static void main(String[] args)
{
int[] arr = new int[]{2,3,1,-4,-4,2};
boolean result = hasSingleCycle(arr);
System.out.println("Does it have single cycle "+result);
}
public static boolean hasSingleCycle(int[] arr)
{
int elementsVisited = 0;
int currentIdx = 0;
while(elementsVisited < arr.length )
{
if(elementsVisited>0 && currentIdx==0)
{
return false;
}
elementsVisited++;
currentIdx = getNextIdx(currentIdx,arr);
}
if(currentIdx==0)
{
return true;
}
else
{
return false;
}
}
public static int getNextIdx(int currentIdx,int[] arr)
{
int jumps = arr[currentIdx];
int nextIdx = (currentIdx+jumps) % arr.length ;
return nextIdx < 0 ? nextIdx+arr.length : nextIdx;
}
}