Linked List Cycle: HashSet of ListNodes

Jay·2022년 5월 19일
0

Grind 120

목록 보기
12/38


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;

Catch Point

  1. Retrieving values and checking if element is contained in collection, much faster to use hash sets
  2. Can construct an array list or hash set of nodes and correctly compare

0개의 댓글