-1

What is the time & space complexity of this method I wrote which returns the first node of the intersection between two singly linked lists (and if none found just null)?

public Node getFirstNodeWhichIntersects(Node node1, Node node2) {
    Node currentPtr1 = node1;
    Node currentPtr2 = node2;   
    Node firstNode = null;
      
    while (currentPtr1 != null) {
       currentPtr2 = node2;
       while (currentPtr2 != null) {
          if (currentPtr1 == currentPtr2) {
              return currentPtr1;
          }     
          currentPtr2 = currentPtr2.next;
       }
       currentPtr1 = currentPtr1.next;
    }
    return firstNode;
}
  • *"which returns the intersection of the first node..."*: I suppose you mean *"which returns the first node of the intersection..."*. – trincot Apr 04 '23 at 21:41
  • BTW, if linked lists don't cycle, a simple algorithm will determine whether two lists have a common tail while examining every node once, and find the start of the tail accessing each node at most once more. – supercat Apr 04 '23 at 22:03
  • @supercat - Are you suggesting my solution is sub-optimal or is missing an edge case? If so, can you provide an example? – programmer0x06 Apr 04 '23 at 23:55

1 Answers1

0

In the worst case the tail node of both lists is the first node that is shared. This algorithm will only find it by testing all possible pairs of nodes (one from the first list, one from the other).

So that gives this algorithm a worst time complexity of O(), where and are the number of nodes in the first and second linked list. Note that there are algorithms for this problem with a time complexity of O(+).

The space complexity is trivial: there are a constant number of variables, each with a constant memory footprint, so the space complexity is O(1).

trincot
  • 317,000
  • 35
  • 244
  • 286