Clean Code For Java Using HashSet
Intuition\n Describe your first thoughts on how to solve this problem. \nThe task is to remove nodes from the linked list whose values appear in the given array
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe task is to remove nodes from the linked list whose values appear in the given array. By storing these values in a HashSet, we can efficiently check whether a node\u2019s value needs to be removed or not.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First, add all elements of the nums array to a HashSet. This allows for O(1) average time complexity when checking if a value exists in the set.\n2. Initialize a dummy node that points to the head of the linked list to handle edge cases where the head node itself might need to be removed.\n3. Use two pointers: prev to track the node before the current one, and temp to iterate through the list.\n4. For each node, check if its value exists in the HashSet:\n5. If it exists, adjust prev.next to skip the current node.\n6. If it doesn\'t exist, move prev to the current node.\n7. Continue this process until the end of the list is reached.\n8. Return dummy.next, which points to the modified linked list.\n# Complexity\n- Time complexity: $$O(n + m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\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        HashSet<Integer> hm= new HashSet<>();\n        for(int i=0;i<nums.length;i++)\n        {\n            hm.add(nums[i]);\n        }\n        ListNode dummy=new ListNode(-1);\n        ListNode prev=dummy;\n        ListNode temp=head;\n        prev.next=temp;\n        while(temp!=null)\n        {\n            if(hm.contains(temp.val))\n            {\n                prev.next=temp.next;\n            }\n            else\n            {\n                prev=temp;\n            }\n            temp=temp.next;\n        }\n\n        return dummy.next;\n    }\n}\n```
['Hash Table', 'Linked List', 'Java']