- Let's start by changing
nums
to aset
(instead of alist
) so that we can match each value along the linked list to the values innums
in constant time (instead oftime, where is the length of nums
) - I think there are two cases we need to account for:
- While the head is in
nums
, sethead = head.next
- Next, keep looping through the subsequent nodes:
- If
node.val
is not innums
, continue to the next node (or returnhead
ifnode.next
isNone
) - If
node.val
is innums
, we need to snip out the current node by settingprev.next = node.next
. So that means we'll also need to keep track of the previous node we've visited
- If
- While the head is in
- Since we're guaranteed that at least one node is not in
nums
, we don't have to account for the special case where there is no head to return - The one sort of "tricky" (if it can be called that) piece is how we keep track of the previous node. I think we can start by setting
prev = head
(once we've skipped ahead to the first node that isn't innums
). Then we can start looping through by settingcurrent = prev.next
and then continue untilcurrent.next
isNone
. - Let's try it!
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def modifiedList(self, nums: List[int], head: Optional[ListNode]) -> Optional[ListNode]:
nums = set(nums)
while head.val in nums:
head = head.next
prev = head
current = head.next
while current is not None:
if current.val in nums:
prev.next = current.next
current = current.next
else:
prev, current = current, current.next
return head
- Given test cases pass
- Off the top of my head I can't think of any particularly interesting edge cases that I'm not accounting for, so I'll just try submitting 🙂
I'll take it! Solved 🎉!