First Thoughts: can determine cycle if we traverse the linked list and checking if the list node was seen before. Also thought of keeping two pointers to compare -> perhaps better time complexity
My Solution:
public class Solution {
public boolean hasCycle(ListNode head) {
ArrayList<ListNode> arr = new ArrayList<>();
while(head!=null) {
if (arr.contains(head)) return true;
arr.add(head);
head = head.next;
}
return false;
}
}
Improved Solution:
Set<ListNode> seenNodes = new HashSet<>();
while (head!=null) {
if (seenNodes.contains(head) return true;
seenNodes.add(head);
head = head.next;
}
return false;