educative.io

Why for loop initialization doesn't work here?

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

Hi @Kishore_S ,

The solution you have given is correct and working even on leetcode. I am unable to figure out why you have posted this solution, can you please explain what do you actually want to ask? Maybe I am missing the point. Thank you so much for contacting with us.