Problem statement

https://binarysearch.com/problems/Linked-List-Delete-Last-Occurrence-of-Value/

Solution

Add dummy variable in the beginnig. Then iterate through elements and keep location of element before element with value target. In the end, do prev_loc.next = prev_loc.next.next.

Complexity

It is O(n) for time and O(1) for additional space.

Code

class Solution:
    def solve(self, node, target):
        dummy = LLNode(None)
        dummy.next = node

        head = dummy
        prev_loc = None
        while dummy.next:
            if dummy.next.val == target:
                prev_loc = dummy
            dummy = dummy.next

        if prev_loc:
            prev_loc.next = prev_loc.next.next
        return head.next