1575. Two-Way Value Purge

Easy1.5 points estimatedDoubly-Linked ListLinked List

A browser history is stored as a doubly linked list, and every visit to one unwanted page value must be erased. Given head of a doubly linked list (each node has val, next and prev) and an integer v, remove every node whose value equals v, repairing both the next and the prev links of the neighbours, and return the new head. If nothing remains the answer is null, and if no node matches the list is unchanged. The new head must have a null prev and the last node a null next. The list has 0 to 1000 nodes. Aim for O(n) time and O(1) extra space.

Example 1

Input:
head = [1,2,6,3,4,5,6], v = 6
Output:
[1,2,3,4,5]
Explanation:

Both 6s are unlinked, leaving 1,2,3,4,5.

Example 2

Input:
head = [7,7,7], v = 7
Output:
[]
Explanation:

Every node matches, so the list becomes empty.

Example 3

Input:
head = [1,2,3], v = 9
Output:
[1,2,3]
Explanation:

No node holds 9, so nothing changes.

Constraints

0 ≤ length ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…