Optimized Java Solution using HashSet for O(1)
Approach:\n\n- Convert the nums array into a HashSet to enable O(1) lookup for checking whether a value exists in nums.\n- Traverse the linked list and only add
# **Approach:**\n\n- Convert the nums array into a HashSet to enable O(1) lookup for checking whether a value exists in nums.\n- Traverse the linked list and only add nodes to the result list if their value is not in the nums set.\n- Use a dummy node to simplify list manipulation, ensuring that the head of the new list is easily accessible.\n- At the end of traversal, terminate the list properly to avoid any dangling references.\n\n# ****Time complexity:****\n- **O(n + m)** where n is the number of nodes in the linked list and m is the length of the nums array:\n- **O(m)** to create the **HashSet** from nums.\n- **O(n)** to traverse the **linked list** and build the new list.\n\n# **Space complexity:**\n- O(m) for the HashSet storing nums.\n- O(1) additional space for the list traversal.\n\n# Code\n```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n    public ListNode modifiedList(int[] nums, ListNode head) {\n\n        // Convert nums array to a HashSet for O(1) lookup time\n        Set<Integer> numSet = new HashSet<>();\n        for (int num : nums) {\n            numSet.add(num);\n        }\n\n        // Dummy node to start the filtered list\n        ListNode dummy = new ListNode(-1);\n        ListNode temp = dummy; // Temporary pointer to form the new list\n\n        // Traverse the linked list directly\n        while (head != null) {\n            // If the value is NOT in nums, add the node to the result list\n            if (!numSet.contains(head.val)) {\n                temp.next = head; // Link the node to the new list\n                temp = temp.next; // Move temp to the next node\n            }\n            head = head.next; // Move to the next node in the original list\n        }\n\n        // Terminate the list properly\n        temp.next = null;\n\n        // Return the head of the new list (skipping the dummy node)\n        return dummy.next;\n    }\n}\n```
['Linked List', 'Java']