Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: From a sorted linked list, delete EVERY value that appears more than once (keep only distinct values).

Problem: From a sorted linked list, delete EVERY value that appears more than once (keep only distinct values).
class N:
    def __init__(s, v, nx=None): s.v, s.nx = v, nx
def dedup(h):
    dummy = N(0, h); prev = dummy
    while h:
        if h.nx and h.nx.v == h.v:
            while h.nx and h.nx.v == h.v: h = h.nx
            prev.nx = h.nx
        else: prev = prev.nx
        h = h.nx
    return dummy.nx
h = None
for v in reversed([1, 1, 2, 3, 3, 3, 4, 5, 5]): h = N(v, h)
h = dedup(h); out = []
while h: out.append(h.v); h = h.nx
print(out)
What is printed?
  1. A. [1, 2, 3, 4, 5]
  2. B. [2, 4]
  3. C. [2, 3, 4]
  4. D. [1, 2, 4, 5]

Correct answer: B. [2, 4]

Unlike plain de-duplication, every copy of a repeated value is removed: 1, 3 and 5 all appear more than once, leaving [2, 4]. The dummy head handles the case where the first value is a duplicate.

More Coding Interview Problems questions

Exams that ask this topic