Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: From a sorted linked list delete EVERY value that occurs more than once (keep only values that appear exactly once).

Problem: From a sorted linked list delete EVERY value that occurs more than once (keep only values that appear exactly once).
class Node:
    def __init__(self, v, nxt=None): self.v, self.next = v, nxt
def build(xs):
    head = None
    for x in reversed(xs): head = Node(x, head)
    return head
def show(h):
    out = []
    while h: out.append(h.v); h = h.next
    return out
def dedup_all(head):
    dummy = Node(0, head); prev = dummy
    while head:
        if head.next and head.next.v == head.v:
            while head.next and head.next.v == head.v:
                head = head.next
            prev.next = head.next
        else:
            prev = prev.next
        head = head.next
    return dummy.next
print(show(dedup_all(build([1, 1, 2, 3, 3, 3, 4, 5, 5]))), show(dedup_all(build([7, 7]))))
What is printed?
  1. A. [2, 4] []
  2. B. [2, 3, 4] []
  3. C. [2, 4] [7]
  4. D. [1, 2, 3, 4, 5] [7]

Correct answer: A. [2, 4] []

A dummy node lets the head itself be deleted. When a run of equal values is found, head skips to its last node and prev.next jumps past the whole run; prev only advances over values that are unique. [1,1,2,3,3,3,4,5,5] keeps 2 and 4; [7, 7] becomes empty (without the dummy, deleting the head run is awkward). Keeping one copy of each value is the different 'remove duplicates' task. O(n).

More Coding Interview Problems questions

Exams that ask this topic