I was trying to solve a problem from leetcode using golang.
Here is the first solution I wrote
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(head *ListNode) *ListNode {
mp := make(map[*ListNode]bool)
temp := head
for _, exists := mp[temp]; temp != nil; temp = temp.Next {
if exists {
return temp
}
mp[temp] = true
}
return nil
}
But this wasn’t updating the map, then I tried this:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(head *ListNode) *ListNode {
mp := make(map[*ListNode]bool)
temp := head
for ; temp != nil; temp = temp.Next {
_, exists := mp[temp];
if exists {
return temp
}
mp[temp] = true
}
return nil
}
It worked, I couldn’t understand the behaviour, why it doesn’t work in the first case?
Type your question above this line.
Course: https://www.educative.io/collection/10370001/6289391964127232