Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Linked List Cycle

Posted on January 18, 2018July 26, 2020 by braindenny

Linked List Cycle



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #twopointer, #linkedlist, #floydcycle

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

Follow up:
Can you solve it without using extra space?

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## https://code.dennyzhang.com/linked-list-cycle
# 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
        """
        ## Idea: 2 pointers. Each time, p1 move 1 step, p2 move 2 step. 
        ##         If it has a cycle(not only it's a circle), p1 and p2 will meet. 
        ##         Otherwise p1 and p2 won't.
        ## Complexity: Time O(n), Space O(1)
        ##
        ##     n1    ->   n2    -> n3
        ##     p1
        ##                p2
        if head is None or head.next is None:
            return False
        p1 = head
        p2 = head.next
        while (p1 is not None) and (p2 is not None) and (p2 != p1):
            p1 = p1.next
            if (p2.next is None) or (p2.next is None):
                p2 = None
            else:
                p2 = p2.next.next

        return  (p1 is not None) and (p2 is not None) and (p2 == p1)
linkedin
github
slack

Post Views: 3
Posted in BasicTagged #floydcycle, #inspiring, #linkedlist, #twopointer

Post navigation

LeetCode: Merge Two Sorted Lists
LeetCode: Number Complement

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.