- 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 of$O(n)$ time, where$n$ is the length ofnums
) - 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 = nextclassSolution: defmodifiedList(self, nums: List[int], head: Optional[ListNode]) ->Optional[ListNode]: nums=set(nums) whilehead.valinnums: head=head.nextprev=headcurrent=head.nextwhilecurrentisnotNone: ifcurrent.valinnums: prev.next=current.nextcurrent=current.nextelse: prev, current=current, current.nextreturnhead
- 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 🎉!