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?- A. [2, 4] []
- B. [2, 3, 4] []
- C. [2, 4] [7]
- 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
- Problem: Reorder a list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place: find the middle, reverse the second half, then interleave…
- Problem: Find the area of the largest all-'1' rectangle in a binary grid by treating each row as the base of a histogram and running the…
- Problem: Does a price series contain a '132' pattern – indices i < j < k with a[i] < a[k] < a[j]? Scan from the right with a decreasing…
- Problem: Delete repeated letters so each letter appears once, and among all such results return the lexicographically smallest (a…
- Problem: A game board has scores a[0..n−1]; from cell i you may jump forward 1..k cells. Starting at 0 and ending at n − 1, maximise the…
- Problem: A council of two parties, R and D, votes in rounds in seat order. On their turn a member bans the next opposing member who has…