Zack Shorts - Interview Prep
GithubLinkedInLeetCode
  • leetcode
    • 0001 - Two Sum
    • 0002 - Add Two Numbers
    • 0003 - Longest Substring Without Repeating Characters
    • 0004 - Median of Two Sorted Arrays
    • 0005 - Longest Palindromic Substring
    • 0006 - ZigZag Conversion
    • 0007 - Reverse Integer
    • 0009 - Palindrome Number
    • 0011 - Container With Most Water
    • 0013 - Roman to Integer
    • 0014 - Longest Common Prefix
    • 0015 - 3 Sum
    • 0017 - Letter Combinations of a Phone Number
    • 0019 - Remove Nth Node From End of List
    • 0020 - Valid Parentheses
    • 0021 - Merge Two Sorted Lists
    • 0022 - Generate Parentheses
    • 0026 - Remove Duplicates from Sorted Array
    • 0027 - Remove Element
    • 0028 - Implement strStr()
    • 0033 - Searching in Rotated Sorted Array
    • 0034 - Find First and Last Position of Element in Sorted Array
    • 0035 - Search Insert Position
    • 0036 - Valid Sudoku
    • 0039 - Combination Sum
    • 0040 - Combination Sum II
    • 0042 - Multiply Strings
    • 0045 - Jump Game II
    • 0046 - Permutations
    • 0047 - Permutations II
    • 0048 - Rotate Image
    • 0049 - Group Anagrams
    • 0053 - Maximum Subarray
    • 0055 - Jump Game
    • 0056 - Merge Intervals
    • 0058 - Length of Last Word
    • 0059 - Spiral Matrix II
    • 0062 - Unique Paths
    • 0066 - Plus One
    • 0067 Add Binary
    • 0069 - Sqrt(x)
    • 0070 - Climbing Stairs
    • 0072 - Edit Distance
    • 0074 - Search a 2D Matrix
    • 0075 - Sort Colors
    • 0076 - Design HashMap
    • 0077 - Combinations
    • 0078 - Subsets
    • 0079 - Word Search
    • 0082 - Remove Duplicates from Sorted List II
    • 0083 - Remove Duplicates from Sorted List
    • 0088 - Merge Sorted Array
    • 0090 - Subsets II
    • 0091 - Decode Ways
    • 0094 - Binary Tree Inorder Traversal
    • 0098 - Validate Binary Search Tree
    • 0100 - Same Tree
    • 0101 - Symmetric Tree
    • 0102 - Binary Tree Level Order Traversal
    • 0104 - Maximum Depth of Binary Tree
    • 0108 - Convert Sorted Arary to Binary Search Tree
    • 0110 - Balance Binary Tree
    • 0111 - Minimum Depth of Binary Tree
    • 0112 - Path Sum
    • 0116 - Populating Next Right Pointers in Each Node
    • 0117 - Populating Next Right Pointers in Each Node 2
    • 0118 - Pascal's Triangle
    • 0119 - Pascal's Triangle II
    • 0120 - Triangle
    • 0121 - Best Time to Buy and Sell Stock
    • 0130 - Surrounded Regions
    • 0136 - Single Number
    • 0139 - Word Break
    • 0141 - Linked List Cycle
    • 0142 - Linked List Cycle 2
    • 0144 - Binary Tree Preorder Traversal
    • 0145 - Binary Tree Postorder Traversal
    • 0146 - LRU Cache
    • 0149 - Max Points on a Line
    • 0152 - Maximum Product Subarray
    • 0153 - Find Minimum in Rotated Sorted Array
    • 0160 - Intersection of Two Linked Lists
    • 0162 - Find Peak Element
    • 0167 - Two Sum II - Input Array Is Sorted
    • 0169 - Majority Element
    • 0187 - Repeated DNA Subsequences
    • 0189 - Rotate Array
    • 0190 - Reverse Bits
    • 0191 - Number of 1 Bits
    • 0198 - House Robber
    • 0200 - Number of Islands
    • 0201 - Bitwise AND of Numbers Range
    • 0202 - Happy Number
    • 0203 - Remove Linked List Elements
    • 0206 - Reverse Linked List
    • 0209 - Minimum Size Subarray Sum
    • 0213 - House Robber II
    • 0217 - Contains Duplicates
    • 0226 - Invert Binary Tree
    • 0231 - Power of Two
    • 0232 - Implement Queue using Stacks
    • 0235 - Lowest Common Ancestor of a Binary Search Tree
    • 0238 - Product of Sorted Array Except Self
    • 0240 - Search a 2D Matrix II
    • 0242 - Valid Anagram
    • 0278 - First Bad Version
    • 0283 - Move Zeroes
    • 0290 - Word Pattern
    • 0300 - Longest Increasing Subsequence
    • 0322 - Coin Change
    • 0334
    • 0343 - Integer Break
    • 0344 - Reverse String
    • 0350 - Intersection of Two Arrays II
    • 0383 - Ransom Note
    • 0384 - Shuffle an Array
    • 0387 - First Unique Character in a String
    • 0409 - Longest Palindrome
    • 0413 - Arithmetic Slices
    • 0415 - Add String
    • 0435 - Non-overlapping Intervals
    • 0438 - Find All Anagrams in a String
    • 0485 - Max Consecutive Ones
    • 0542 - Zero One Matrix
    • 0547 - Number of Provinces
    • 0557 - Reverse Words in a String III
    • 0560 - Subarray Sum Equals K
    • 0556 - Reshape the Matrix
    • 0567 - Permutation in String
    • 572 - Subtree of Another Tree
    • 0583 - Delete Operation for Two Strings
    • 0617 - Merge Two Binary Trees
    • 0653 - Two Sum IV - Input is a BST
    • 0673 - Number of Longest Increasing Subsequence
    • 0695 - Max Area of Island
    • 0700 - Search in a Binary Search Tree
    • 0701 - Insert into a Binary Search Tree
    • 0704 - Binary Search
    • 0713 - Subarray Product Less Than K
    • 0733 - Flood Fill
    • 0763 - Partition Labels
    • 0784 - Letter Case Permutation
    • 797 - All Paths From Source to Target
    • 0844 - Backspace String Compare
    • 0876 - Middle of the Linked List
    • 0937 - Reorder Data in Log Files
    • 0938 - Range Sum of BST
    • 0941 - Valid Mountain Array
    • 0977 - Squares of a Sorted Array
    • 0986 - Interval List Intersections
    • 0542 - 01 Matrix
    • 1041 - Robot Bounded in Circle
    • 1089 - Duplicate Zeros
    • 1091 - Shortest Path in Binary Matrix
    • 1143 - Longest Common Subsequence
    • 1295 - Find Numbers with Even Number of Digits
    • 1346 - Check if N and its Double Exist
    • 1446 - Consecutive Characters
Powered by GitBook
On this page
  • Examples
  • Constraints
  • Java Solution
  • Tortoise and Hare (O(1) space)
  • HashSet
  1. leetcode

0142 - Linked List Cycle 2

Previous0141 - Linked List CycleNext0144 - Binary Tree Preorder Traversal

Last updated 3 years ago

Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

Do not modify the linked list.

Examples

Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node.

Input: head = [1,2], pos = 0 Output: tail connects to node index 0 Explanation: There is a cycle in the linked list, where tail connects to the first node.

Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list.

Constraints

  • The number of the nodes in the list is in the range [0, 104].

  • -105 <= Node.val <= 105

  • pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?

Java Solution

Tortoise and Hare (O(1) space)

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    private ListNode getIntersect(ListNode head) {
        ListNode tortoise = head;
        ListNode hare = head;

        while (hare != null && hare.next != null) {
            tortoise = tortoise.next;
            hare = hare.next.next;
            if (tortoise == hare) {
                return tortoise;
            }
        }

        return null;
    }
    
    public ListNode detectCycle(ListNode head) {
        if (head == null) return null;

        ListNode intersect = getIntersect(head);
        if (intersect == null) {
            return null;
        }

        ListNode ptr1 = head;
        ListNode ptr2 = intersect;
        while (ptr1 != ptr2) {
            ptr1 = ptr1.next;
            ptr2 = ptr2.next;
        }

        return ptr1;
    }
}

HashSet

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        Set<ListNode> visited = new HashSet<ListNode>();
        
        ListNode node = head;
        
        while(node != null) {
            if(visited.contains(node)) return node;
            
            visited.add(node);
            node = node.next;
        }
        return null;
    }
}
0142 - Linked List Cycle 2