LeetCode #141 Linked List Cycle

Problem

Given a linked list, determine if it has a cycle in it.

Solution

Method: Two Pointer

Time Complexity: O(n)

Space Complexity: O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow = head
fast = head

while slow and fast.next and fast.next.next:
fast = fast.next.next
if slow == fast:
return True
else:
slow = slow.next

return False

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

# This algorithm is more concise
class Solution(object):
def hasCycle(self, head):
slow = fast = head

while fast and fast.next:
fast = fast.next.next
slow = slow.next

if slow == fast:
return True

return False

Pitfalls

  • the input linked list has no cycle => return false
  • the input linked list has cycle => return true