As reported: PayPal SDE 3 (Python), DSA round (2025, 45 minutes): given a list of values, build a linked list; then, given a tuple (value to remove, value to add at a different place), remove all occurrences of the first value and add the second; working code was expected.
Implement two functions on a singly linked list:
buildList(values)— build a list holdingvaluesin order and return its head (nullfor an empty list).removeAndAdd(head, remove, add)— delete every node whose value isremove, then append a new node with valueaddat the tail. Return the new head.
Example 1
values = [1,2,3,2,4], (remove, add) = (2, 9)
buildList -> 1 -> 2 -> 3 -> 2 -> 4
removeAndAdd -> 1 -> 3 -> 4 -> 9
Example 2
values = [5,5,5], (remove, add) = (5, 1)
buildList -> 5 -> 5 -> 5
removeAndAdd -> 1
Constraints: 0 ≤ values.length ≤ 10^5; values are integers in [-10^9, 10^9].
Code runner format: line 1 is values (JSON array), line 2 is [remove, add]. The harness prints the list after buildList, then after removeAndAdd, each as a JSON array.
Clarifications
- If
removedoes not occur, nothing is deleted;addis still appended. - If every node is deleted (or the list was empty), the result is the single node
add.