Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft
Remove the n-th node from the END of a linked list in one pass, using a dummy node and a gap of n between two pointers. What is printed?
Remove the n-th node from the END of a linked list in one pass, using a dummy node and a gap of n between two pointers. What is printed?
def remove_nth(h, n):
d = N(0, h); fast = slow = d
for _ in range(n + 1): fast = fast.nx
while fast: fast, slow = fast.nx, slow.nx
slow.nx = slow.nx.nx
return d.nx
print(vals(remove_nth(build([86, 68, 13, 45, 70, 55, 54]), 4)))- A. [86, 68, 13, 70, 55, 54]
- B. [86, 68, 45, 70, 55, 54]
- C. [86, 68, 13, 45, 55, 54]
- D. [68, 86, 13, 70, 55, 54]
Correct answer: A. [86, 68, 13, 70, 55, 54]
fast starts n + 1 steps ahead of slow (both from the dummy), so when fast falls off the end, slow is just before the node to delete; the dummy also handles deleting the head. Output: [86, 68, 13, 70, 55, 54].
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
- Z-array: z[i] is the length of the longest common prefix of s and s[i:], with z[0] defined as 0. What is printed? python s = "bbaaaabab" z…
- Asteroids move along a line: positive values move right, negative move left; on collision the smaller (by absolute value) explodes, equal…
- A difference array is used for q range-increment updates followed by one final read of all n values. What is the total time?
- Top-down merge sort (split at mid = n // 2, recurse, then merge, stopping comparisons when one side runs out) sorts [10, 29, 19, 28, 32…
- The Boyer–Moore majority vote (candidate/counter, no verification pass) runs on [3, 3, 3, 3, 7, 3, 7, 5, 5]. What candidate and final…
- A prefix-sum array P of A (P[0] = 0, P[i] = A[0] + … + A[i − 1]) is built. Which expression gives the sum A[l] + … + A[r] (0-based…