Data Structures & AlgorithmsHardGATE CS · DSA
Delete duplicates from a SORTED linked list. Version A keeps one copy of each value; version B removes every value that appears more than once. What is printed?
Delete duplicates from a SORTED linked list. Version A keeps one copy of each value; version B removes every value that appears more than once. What is printed?
def keep_one(h):
c = h
while c and c.nx:
if c.v == c.nx.v: c.nx = c.nx.nx
else: c = c.nx
return h
def drop_all(h):
d = p = N(0, h)
while p.nx:
q = p.nx
if q.nx and q.v == q.nx.v:
while q.nx and q.v == q.nx.v: q = q.nx
p.nx = q.nx
else: p = p.nx
return d.nx
print(vals(keep_one(build([2, 2, 2, 3, 4, 4, 6, 6, 6]))), vals(drop_all(build([2, 2, 2, 3, 4, 4, 6, 6, 6]))))- A. [2, 3, 6, 4] [3]
- B. [2, 4, 3, 6] [3]
- C. [2, 3, 4, 6] [3]
- D. [2, 2, 3, 4, 6, 6] [3]
Correct answer: C. [2, 3, 4, 6] [3]
keep_one advances only when the next value differs, so runs of 3+ copies collapse fully; drop_all skips a whole run and links past it. Output: [2, 3, 4, 6] [3].
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
- Trains occupy a platform from arrival to departure INCLUSIVE, so a train arriving at the same minute another departs needs a separate…
- Counting sort on [1, 1, 2, 1, 0, 3, 3, 0, 2, 0] (values 0–4) builds count[], turns it into cumulative counts, then scans the input from…
- What is the length of the shortest contiguous subarray of [1, 3, 1, 8, 7, 3, 4, 7, 1, 2] whose sum is at least 20? (All values are…
- Count zero-sum contiguous subarrays with a prefix-sum frequency map. What is printed? python from collections import defaultdict a = [0…
- Rotate a square matrix 90° clockwise in place by transposing and then reversing each row. What is printed? python m = [[1, 2, 3], [4, 5…
- For the binary array [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1], replace 0 by −1 and use prefix sums with a first-occurrence map. What is the…