Skip to content

Commit ced52b4

Browse files
committed
Added solution to Linked List Cycle problem
1 parent dc7ce8d commit ced52b4

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
Problem: Linked List Cycle II
3+
Platform: Leetcode
4+
Problem Code: 142
5+
Difficulty: Medium
6+
Link: https://leetcode.com/problems/linked-list-cycle-ii/description/
7+
8+
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
9+
10+
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.
11+
12+
Do not modify the linked list.
13+
14+
15+
16+
Example 1:
17+
Input: head = [3,2,0,-4], pos = 1
18+
Output: tail connects to node index 1
19+
Explanation: There is a cycle in the linked list, where tail connects to the second node.
20+
21+
Example 2:
22+
Input: head = [1,2], pos = 0
23+
Output: tail connects to node index 0
24+
Explanation: There is a cycle in the linked list, where tail connects to the first node.
25+
26+
Example 3:
27+
Input: head = [1], pos = -1
28+
Output: no cycle
29+
Explanation: There is no cycle in the linked list.
30+
31+
Constraints:
32+
* The number of the nodes in the list is in the range [0, 104].
33+
* -105 <= Node.val <= 105
34+
* pos is -1 or a valid index in the linked-list.
35+
36+
Approach:
37+
1. Created a map weith its key as Node, and value as int.
38+
2. We measure how many time a node is being accesed.
39+
3. If frequency of arrivals is more than 1, then we have a cycle.
40+
Time Complexity: O(n)
41+
Space Complexity: O(n)
42+
43+
Contributor: SamaKool
44+
*/
45+
46+
/**
47+
* Definition for singly-linked list.
48+
* struct ListNode {
49+
* int val;
50+
* ListNode *next;
51+
* ListNode(int x) : val(x), next(NULL) {}
52+
* };
53+
*/
54+
class Solution {
55+
public:
56+
ListNode *detectCycle(ListNode *head) {
57+
ListNode* temp = head;
58+
map<ListNode*, int> mpp;
59+
if(head == NULL) return NULL;
60+
if(head->next == NULL) return NULL;
61+
while(mpp[temp] != 2){
62+
if(temp->next == nullptr) return NULL;
63+
mpp[temp]++;
64+
temp = temp->next;
65+
}
66+
if(mpp[temp] == 2) return temp;
67+
else return NULL;
68+
69+
}
70+
};

0 commit comments

Comments
 (0)