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]))))
  1. A. [2, 3, 3, 4, 4] [2]
  2. B. [2, 4, 3] [2]
  3. C. [3, 2, 4] [2]
  4. 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].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic