0

I am solving a leetcode problem to find the intersection point in a linkedlist. When I use the list it gives me time limit exceed error but when I use set it gives me the answer. As each node in LinkedList is different both set and list would have the same element

Below is my code

def getIntersectionNode(self, headA: ListNode, headB: ListNode):
        nodes = set()
        while headA != None:
            nodes.add(headA)
            headA = headA.next

        while headB != None:
            if headB in nodes:
                return headB
            headB = headB.next
        return None

What is the reason for error to occur when using list instead of set.

2 Answers 2

1

In python sets are faster for checking if they contain a certain element. The following will be faster if nodes is a set.

if headB in nodes:

But for example iterating over a set would be slower than iterating over a list.

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

Comments

0

The in operator is implemented differently for a set and a list.

  • For a list, the code must iterate over the entire list to check each element, potentially a linear-time operation.

  • For a set, the code checks if a given element is present using its hash code in constant time (on average).

Suppose A has m nodes and B has n nodes, and the lists don't intersect (worst-case scenario). If nodes is a list, the algorithm will have to iterate over all the nodes of A for each node in B, giving a time complexity of Θ(m×n). By contrast, when using a set the time complexity will be Θ(m+n). For large values of m and n, this makes a big difference in the runtime of the function.

Here are some references on how hash tables (the basis for Python's set and dict data structures) work:

4 Comments

@AjinkyaGadgil You're welcome! If this answered your question you can click the "check mark" next to the answer to mark the question as solved.
I have one question though. How exactly the set checks in a larger list?
That's a complicated question to answer, I'll add a reference in my answer so you can read about how hash tables work.
Thanks. I will check the links.

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.