The Indian Engineer

Problem 3217 Delete Nodes From Linked List Present in Array

Posted on Last edited 2 mins

Linked-List Pointers

Problem Statement

Link - Problem 3217

Question

You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums.

Example 1

Input: nums = [1,2,3], head = [1,2,3,4,5]

Output: [4,5]

Example 2

Input: nums = [1], head = [1,2,1,2,1,2]

Output: [2,2,2]

Example 3

Input: nums = [5], head = [1,2,3,4]

Output: [1,2,3,4]

Constraints

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* modifiedList(vector<int>& nums, ListNode* head) {
       unordered_set<int> s(nums.begin(),nums.end());

        ListNode * ans=head;

        while(ans!=nullptr && s.find(ans->val)!=s.end()){
            ans=ans->next;
        }

        head=ans;

        while(head!=nullptr && head->next!=nullptr){
            if(s.find(head->next->val)!=s.end()){
                head->next=head->next->next;
            }
            else{
                head=head->next;
            }
        }
        return ans;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Pointer Traversal O(n) O(n)

Explanation

1. Intuition

2. Implementation