Deduplicate a Linked List
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Take-home Project
Quick Answer: This question evaluates proficiency in linked list manipulation, in-place data structure modification, and reasoning about time-space trade-offs for removing duplicate elements.
Part 1: Deduplicate a Sorted Singly Linked List
Constraints
- 0 <= len(values) <= 200000
- -10^9 <= values[i] <= 10^9
- `values` is sorted in non-decreasing order
Examples
Input: []
Expected Output: []
Explanation: Edge case: an empty list stays empty.
Input: [5]
Expected Output: [5]
Explanation: Edge case: a single node has no duplicates to remove.
Input: [7, 7, 7, 7]
Expected Output: [7]
Explanation: All nodes have the same value, so only the first remains.
Input: [1, 2, 3, 4]
Expected Output: [1, 2, 3, 4]
Explanation: No duplicates exist, so the list is unchanged.
Input: [1, 1, 2, 3, 3, 3, 4, 4, 5]
Expected Output: [1, 2, 3, 4, 5]
Explanation: Repeated adjacent values are removed, leaving one copy of each.
Solution
def solution(values):
class ListNode:
__slots__ = ('val', 'next')
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def build_linked_list(vals):
dummy = ListNode()
tail = dummy
for v in vals:
tail.next = ListNode(v)
tail = tail.next
return dummy.next
def to_list(head):
result = []
while head is not None:
result.append(head.val)
head = head.next
return result
head = build_linked_list(values)
current = head
while current is not None and current.next is not None:
if current.val == current.next.val:
current.next = current.next.next
else:
current = current.next
return to_list(head)