Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (finding the intersection node of two linked lists by switching heads)
What is printed? (finding the intersection node of two linked lists by switching heads)
class N:
def __init__(s, v, n=None): s.v, s.n = v, n
common = N(8, N(4, N(5)))
a = N(4, N(1, common))
b = N(5, N(6, N(1, common)))
p, q, steps = a, b, 0
while p is not q:
p = p.n if p else b
q = q.n if q else a
steps += 1
print(p.v, steps)- A. 8 9
- B. 1 9
- C. 8 5
- D. 8 11
Correct answer: A. 8 9
Each pointer walks its own list, takes one step onto None, then restarts at the head of the other list, so both cover the same distance before meeting at the first shared node: (5 + 1) + 3 = 9 steps for p and (6 + 1) + 2 = 9 for q. They meet at the node with value 8 – the two nodes with value 1 are different objects, which is why identity (is), not ==, is compared. O(m + n), O(1) space.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (Java String vs StringBuilder) java String s = "ab"; s.concat("cd"); StringBuilder sb = new StringBuilder("ab")…
- What is printed? (counting sort on small values) python a = [4, 1, 3, 4, 2, 1, 0, 4] cnt = [0] 5 for x in a: cnt[x] += 1 for i in range(1…
- How many swaps does this bubble sort make, and how many passes run? python a = [5, 1, 4, 2, 8] swaps = passes = 0 for i in range(len(a)…
- Insertion sort counts element shifts. What is printed? python a = [3, 7, 1, 5, 2] shifts = 0 for i in range(1, len(a)): key, j = a[i], i…
- Quick sort with Lomuto partition (last element as pivot). What is the array after the FIRST partition, and the pivot's final index? python…
- Merge two sorted halves and count comparisons. What is printed? python L, R = [1, 4, 6, 9], [2, 3, 10] i = j = comps = 0; out = [] while i…