Data Structures & AlgorithmsHardFlipkart/Uber OA · placement

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([1, 1, 2, 2, 4, 4, 6, 6, 6]))), vals(drop_all(build([1, 1, 2, 2, 4, 4, 6, 6, 6]))))
  1. A. [1, 2, 4, 6, 6] []
  2. B. [1, 2, 4, 6] []
  3. C. [1, 4, 2, 6] []
  4. D. [2, 1, 4, 6] []

Correct answer: B. [1, 2, 4, 6] []

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: [1, 2, 4, 6] [].

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

Exams that ask this topic