|
| 1 | +/* |
| 2 | +Asked by - PayTM, Amazon, MakeMyTrip, Snapdeal, VMWare, Samsung, Qualcomm, Walmart. |
| 3 | +
|
| 4 | +Given a linked list, check if the the linked list has a loop. |
| 5 | +
|
| 6 | +Create a function that returns true if a linked list contains a cycle, or false if it terminates |
| 7 | +Usually we assume that a linked list will end with a null next pointer, for example: |
| 8 | +A -> B -> C -> D -> E -> null |
| 9 | +A 'cycle' in a linked list is when traversing the list would result in visiting the same nodes over and over |
| 10 | +This is caused by pointing a node in the list to another node that already appeared earlier in the list. Example: |
| 11 | +A -> B -> C |
| 12 | + ^ | |
| 13 | + | v |
| 14 | + E <- D |
| 15 | +Example code: |
| 16 | +const nodeA = new Node('A'); |
| 17 | +const nodeB = nodeA.next = new Node('B'); |
| 18 | +const nodeC = nodeB.next = new Node('C'); |
| 19 | +const nodeD = nodeC.next = new Node('D'); |
| 20 | +const nodeE = nodeD.next = new Node('E'); |
| 21 | +hasCycle(nodeA); // => false |
| 22 | +nodeE.next = nodeB; |
| 23 | +hasCycle(nodeA); // => true |
| 24 | +Constraint 1: Do this in linear time |
| 25 | +Constraint 2: Do this in constant space |
| 26 | +Constraint 3: Do not mutate the original nodes in any way |
| 27 | +Hint: Search for Floyd's Tortoise and Hare algorithm. |
| 28 | +*/ |
| 29 | + |
| 30 | +function Node(data){ |
| 31 | + this.data = data |
| 32 | + this.next = null |
| 33 | +} |
| 34 | + |
| 35 | +// You can read more on cycle detection at https://en.wikipedia.org/wiki/Cycle_detection |
| 36 | +// but the main takeaway is that if hare moves twice as fast as tortoise |
| 37 | +// then a loop would be identifiable as the hare will eventually catch up with the tortoise. |
| 38 | + |
| 39 | +const hasCycle = (head) => { |
| 40 | + let tortoise = head |
| 41 | + let hare = head |
| 42 | + do{ |
| 43 | + if(hare.next === null) |
| 44 | + return false |
| 45 | + hare = hare.next |
| 46 | + if(hare.next === null) |
| 47 | + return false |
| 48 | + hare = hare.next |
| 49 | + tortoise = tortoise.next |
| 50 | + }while(tortoise !== hare) |
| 51 | + return true |
| 52 | +} |
| 53 | + |
| 54 | +const n1 = new Node('A'); |
| 55 | +const n2 = n1.next = new Node('B'); |
| 56 | +const n3 = n2.next = new Node('C'); |
| 57 | +const n4 = n3.next = new Node('D'); |
| 58 | +const n5 = n4.next = new Node('E'); |
| 59 | +console.log(hasCycle(n1)); // => false |
| 60 | +n5.next = n2; |
| 61 | +console.log(hasCycle(n1)); // => true |
0 commit comments