Skip to content

Commit

Permalink
Complete hasCycle in key-concepts.js
Browse files Browse the repository at this point in the history
  • Loading branch information
fay-jai committed Feb 17, 2015
1 parent 6307e32 commit 0278734
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions key-concepts.js
Original file line number Diff line number Diff line change
Expand Up @@ -782,4 +782,51 @@ var getElementsByClassName = function (className, element) {
};

return inner(element, []);
};

/*
* Assignment: Write a function that returns true if a linked list contains a cycle, or false if it terminates somewhere
*
* Explanation:
*
* Generally, we assume that a linked list will terminate in a null next pointer, as follows:
*
* A -> B -> C -> D -> E -> null
*
* A 'cycle' in a linked list is when traversing the list would result in visiting the same nodes over and over
* This is caused by pointing a node in the list to another node that already appeared earlier in the list. Example:
*
* A -> B -> C
* ^ |
* | v
* E <- D
*
* Example code:
*
* var nodeA = Node('A');
* var nodeB = nodeA.next = Node('B');
* var nodeC = nodeB.next = Node('C');
* var nodeD = nodeC.next = Node('D');
* var nodeE = nodeD.next = Node('E');
* hasCycle(nodeA); // => false
* nodeE.next = nodeB;
* hasCycle(nodeA); // => true
*
* Constraint 1: Do this in linear time
* Constraint 2: Do this in constant space
* Constraint 3: Do not mutate the original nodes in any way
*/

var hasCycle = function (node) {
var first = node;
var second = node;

while (first && second) {
if (first === second) return true;

first = node.next;
second = node.next.next;
}

return false;
};

0 comments on commit 0278734

Please sign in to comment.