Posts

Showing posts with the label detect cycle

142. Linked List Cycle II

Image
https://leetcode.com/problems/linked-list-cycle-ii/ Given a linked list, return the node where the cycle begins. If there is no cycle, return  null . To represent a cycle in the given linked list, we use an integer  pos  which represents the position (0-indexed) in the linked list where tail connects to. If  pos  is  -1 , then there is no cycle in the linked list. Note:  Do not modify the linked list. Example 1: 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. Example 2: 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. Example 3: Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list. Follow-up : Can you solve it without using extra space? --- Intuition ...

287. Find the Duplicate Number

https://leetcode.com/problems/find-the-duplicate-number/ Given an array  nums  containing  n  + 1 integers where each integer is between 1 and  n  (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 Example 2: Input: [3,1,3,4,2] Output: 3 Note: You  must not  modify the array (assume the array is read only). You must use only constant,  O (1) extra space. Your runtime complexity should be less than  O ( n 2 ). There is only one duplicate number in the array, but it could be repeated more than once. --- Intuition Numbers are in the array from 1 through N,  If we consider array element to be index to travel to, and remember that  N + 1 elements exists. This means all values point to position that definitely exists, then array will be traversed  infinitely and there is ...

202. Happy Number

https://leetcode.com/problems/happy-number/ Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example:  Input: 19 Output: true Explanation: 1 2 + 9 2 = 82 8 2 + 2 2 = 68 6 2 + 8 2 = 100 1 2 + 0 2 + 0 2 = 1 -- Related problems ugly-number