1

This is a leetcode question 160. intersection of two linked list, where Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. https://leetcode.com/problems/intersection-of-two-linked-lists/

if map[headB]==1 is giving a runtime error in Leetcode. I know if i use 'if headB in map' it works fine, but i want to know why 'if map[headB]==1' gives error. Thank you.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        
        map=dict()
        
        while (headA):
            map[headA]=1
            headA=headA.next
        
        while (headB):
            if map[headB]==1: #why this doesn't work? ('if headB in map' works fine)
                return headB
            headB=headB.next
        
        return None
3
  • Why would you think the two expressions are the same? Commented Jun 19, 2022 at 5:09
  • well technicially they are different. Though both are checking if the headB exists in the dictionary. so i am wondering why only 'headB in map' works Commented Jun 19, 2022 at 5:12
  • It's also important to show what the error is; don't make anyone guess. Commented Jun 19, 2022 at 5:14

1 Answer 1

1

Because if key headB doesn't exist in map, map[headB] will throw a KeyError. It cannot compare something that doesn't exist to one.

Also, you might want to use some other name than just "map", because it shadows the built-in Python function map().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.