Airbnb questions

Linked List Intersection With Cycles

AirbnbHard

Two singly linked lists are described by one shared pool of nodes numbered 0 to n - 1. The list successor holds, for each node i, the index of the node after it, or -1 when i is the last node of its list. A list is named by its head: a node index, or -1 for the empty list. Two lists can run into the same nodes, and a list can loop back on itself, so following successor from a head either reaches -1 or comes round to a node it has already visited. The nodes a head's list consists of are all the nodes visited on that walk, each counted once. Two lists share a node when some node index belongs to both. Build ListIntersector(successor).

Part 1: Do the lists meet

Implement intersects(head_a, head_b): it returns true when the list starting at head_a and the list starting at head_b share at least one node, and false otherwise. A list that is empty shares nothing with anything. Either list can contain a cycle.

Constant extra space is the better answer.

  1. Example 1
    init
    [[1,2,5,4,5,6,-1]]
    operations
    [["intersects",[0,3]],["intersects",[0,-1]],["intersects",[3,3]],["intersects",[3,0]]]
    Output
    [true,false,true,true]

    Why: List A is 0, 1, 2, 5, 6 and list B is 3, 4, 5, 6, so they share nodes 5 and 6 (true). An empty list shares nothing (false). A list shares a node with itself (true), and the answer does not depend on which list comes first.

Constraints

  • 0 <= len(successor) <= 10^5
  • Every value of successor is -1 or a node index; every head is -1 or a node index
  • 1 <= len(operations) <= 100
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Linked List Intersection With Cycles: Airbnb interview question | LoopCoach