Skip to content

Commit

Permalink
Create FindLoopLength.java
Browse files Browse the repository at this point in the history
  • Loading branch information
harshithasudhakar authored Jan 15, 2025
1 parent b304f57 commit 93e67a3
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Linked List/Singly Linked List/FindLoopLength.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Node is defined as:
// class Node{
// int val;
// Node next;
// Node(){
// val =0;
// next = null;
// }
// Node(int x){
// val = x; next = null;
// }
// }

class FindLoopLength{

static int solve(Node root){

if (root == null) return -1;

Node slow = root;
Node fast = root;

while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(fast == slow){
return loopLength(slow);
}
}
return -1;
}

static int loopLength(Node slow){
int count = 1;
Node ptr = slow.next;
while(ptr != slow){
count++;
ptr = ptr.next;
}
return count;
}
}

0 comments on commit 93e67a3

Please sign in to comment.