|
| 1 | +# Find length of Loop |
| 2 | +## Easy |
| 3 | +<div class="problems_problem_content__Xm_eO"><p><span style="font-size:18px">Given a linked list of size <strong>N</strong>. The task is to complete the function <strong>countNodesinLoop() </strong>that checks whether a given Linked List contains a <strong>loop or not </strong>and if the <strong>loop </strong>is present then<strong> return the count of nodes</strong> in a loop or else <strong>return 0. C </strong>is the position of the node to which the last node is connected. If it is 0 then no loop.</span></p> |
| 4 | + |
| 5 | +<p><span style="font-size:18px"><img alt="" src="https://contribute.geeksforgeeks.org/wp-content/uploads/linkedlist.png" style="height:236px; width:512px"> </span></p> |
| 6 | + |
| 7 | +<p><span style="font-size:18px"><strong>Example 1:</strong></span></p> |
| 8 | + |
| 9 | +<pre><span style="font-size:18px"><strong>Input: |
| 10 | +</strong>N = 10 |
| 11 | +value[]={25,14,19,33,10,21,39,90,58,45} |
| 12 | +C = 4 |
| 13 | +<strong>Output: </strong>7<strong> |
| 14 | +Explanation: </strong>The loop is 45->33. So |
| 15 | +length of loop is 33-><em>10</em>->21->39-> |
| 16 | +90->58-><em>45</em> = <strong>7. </strong>The number 33 is |
| 17 | +connected to the last node to form the |
| 18 | +loop because according to the input the |
| 19 | +4<sup>th</sup> node from the beginning(1 based |
| 20 | +index) will be connected to the last |
| 21 | +node for the loop.</span> |
| 22 | +</pre> |
| 23 | + |
| 24 | +<p><span style="font-size:18px"><strong>Example 2:</strong></span></p> |
| 25 | + |
| 26 | +<pre><span style="font-size:18px"><strong>Input: |
| 27 | +</strong>N = 2 |
| 28 | +value[] = {1,0} |
| 29 | +C = 1 |
| 30 | +<strong>Output: </strong>2<strong> |
| 31 | +Explanation: </strong>The length of the loop |
| 32 | +is 2.</span></pre> |
| 33 | + |
| 34 | +<p><span style="font-size:18px"><strong>Your Task:</strong><br> |
| 35 | +The task is to complete the function <strong>countNodesinLoop</strong>() which contains the only argument as reference to head of<strong> linked list </strong>and return the length of the loop ( 0 if there is no loop).</span></p> |
| 36 | + |
| 37 | +<p><span style="font-size:18px"><strong>Expected Time Complexity:</strong> O(N)<br> |
| 38 | +<strong>Expected Auxiliary Space:</strong> O(1)</span></p> |
| 39 | + |
| 40 | +<p><span style="font-size:18px"><strong>Constraints:</strong><br> |
| 41 | +1 <= N <= 500<br> |
| 42 | +0 <= C <= N-1</span></p> |
| 43 | +</div> |
0 commit comments