Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft
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, 3, 3, 3, 3, 4, 4, 4, 4]))), vals(drop_all(build([2, 3, 3, 3, 3, 4, 4, 4, 4]))))- A. [2, 3, 3, 4, 4] [2]
- B. [2, 4, 3] [2]
- C. [3, 2, 4] [2]
- D. [2, 3, 4] [2]
Correct answer: D. [2, 3, 4] [2]
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] [2].
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
- Which data structure gives O(1) worst-case time for inserting and deleting at BOTH ends and also O(1) access by index?
- What is the length of the shortest contiguous subarray of [1, 3, 5, 6, 3, 3, 7, 9, 4, 9] 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 = [1…
- Bubble sort (ascending; each pass compares adjacent pairs left to right and swaps if out of order) is applied to [5, 42, 29, 4, 41, 8, 53…
- Stock prices over 8 days are [27, 32, 42, 42, 35, 66, 59, 31]. The span of day i is the number of consecutive days ending at day i…
- Assertion (A): Binary search runs in O(log n) time on a sorted singly linked list. Reason (R): Binary search halves the search range in…