Open In App

Maximize unique elements in set after K deletions from each array

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given two 0-indexed integer arrays nums1[] and nums2[] of even length N. Remove K elements from nums1[] and K elements from nums2[]. After the removals, insert the remaining elements of nums1 and nums2 into a set S. The task is to return the maximum possible size of the set S.

Examples:

Input: nums1 = [2, 2, 2, 2, 2, 2], nums2 = [2, 2, 2, 3, 3, 3], K = 4
Output: 2
Explanation: We remove 4 occurrences of 2 from nums1 and 3 occurrences of 2 + 1 occurrence of 3 from nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [3,3]. Therefore, s = {2,3}. It can be shown that 2 is the maximum possible size of the set s after the removals.

Input: nums1 = [1,2,3], nums2 = [3,4,5], K = 1
Output: 4
Explanation: We remove 1 occurrence of 3 from nums1 and 1 occurrence of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,2] and nums2 = [4,5]. Therefore, s = {1,2,4,5}. It can be shown that 4 is the maximum possible size of the set s after the removals.

Approach: To solve the problem, follow the below idea:

Firstly, remove all the multiple occurrences of elements in nums1[] leaving single occurrence of all elements. Similarly, remove all the multiple occurrences of elements in nums2[] leaving single occurrence of all elements. After removing the extra occurrences of elements if we still need to remove elements then we can start removing elements which are common in nums1[] and nums2[]. If after removing the common elements, we still need to remove elements then we remove the unique elements. Also keep track of the common elements which are removed from one set so that those elements are not deleted while removing elements from the second set.

Step-by-step algorithm:

  • Initialize two variables, say elementsToRemove1 and elementsToRemove2 to keep track of how many more elements are needed to be deleted from nums1[] and nums2[].
  • Store all the elements of nums1[] in a set, say s1 and all elements of nums2[] in another set, say s2.
  • Subtract extra elements from elementsToRemove1 as elementsToRemove1 -= (N – s1.size()).
  • Subtract extra elements from elementsToRemove2 as elementsToRemove2 -= (N – s2.size()).
  • Now, insert all the common elements in a set, say common.
  • Now, if we need to remove more elements from s1, then remove the common element from s1 otherwise remove the common element from s2.
  • After removal of all the elements, return s1.size() + s2.size() – common.size() as the total remaining elements.

Below is the implementation of the algorithm:

C++
#include <bits/stdc++.h>

using namespace std;

// Function to calculate the maximum size of a set with at
// most k elements from nums1 and nums2
int maximumSetSize(const vector<int>& nums1,
                const vector<int>& nums2, int k)
{

    int n = nums1.size();
    int elementsToRemove1 = k;
    int elementsToRemove2 = k;

    // Create unordered sets to store unique elements from
    // nums1 and nums2
    unordered_set<int> s1(nums1.begin(), nums1.end());
    unordered_set<int> s2(nums2.begin(), nums2.end());
    // Set to store common elements between s1 and s2
    unordered_set<int> common;

    elementsToRemove1 -= (n - s1.size());
    elementsToRemove2 -= (n - s2.size());

    // Find common elements between s1 and s2
    for (int x : s1) {
        if (s2.find(x) != s2.end()) {
            common.insert(x);
        }
    }

    // Keep removing elements till K elements are removed
    // from both the sets
    while (elementsToRemove1 > 0 || elementsToRemove2 > 0) {
        // If more elements are needed to be deleted from s1
        if (elementsToRemove1 > elementsToRemove2) {
            // If we are left with common elements, delete
            // them first
            if (!common.empty()) {
                int ele = *common.begin();
                s1.erase(ele);
                common.erase(ele);
            }
            // Else delete the unique elements
            else {
                int ele = *s1.begin();
                s1.erase(ele);
            }
            elementsToRemove1 -= 1;
        }
        // If more elements are needed to be deleted from s2
        else {
            // If we are left with common elements, delete
            // them first
            if (!common.empty()) {
                int ele = *common.begin();
                s2.erase(ele);
                common.erase(ele);
            }
            // Else delete the unique elements
            else {
                int ele = *s2.begin();
                s2.erase(ele);
            }
            elementsToRemove2 -= 1;
        }
    }
    return s1.size() + s2.size() - common.size();
}

// Driver Code
int main()
{
    // Example input
    vector<int> nums1 = { 1, 2, 3 };
    vector<int> nums2 = { 3, 4, 5 };
    int k = 1;

    // Call the function and display the result
    int result = maximumSetSize(nums1, nums2, k);
    cout << "Output: " << result << endl;

    return 0;
}
Java
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

public class Main {

    // Function to calculate the maximum size of a set with at
    // most k elements from nums1 and nums2
    static int maximumSetSize(Vector<Integer> nums1, Vector<Integer> nums2, int k) {
        int n = nums1.size();
        int elementsToRemove1 = k;
        int elementsToRemove2 = k;

        // Create sets to store unique elements from nums1 and nums2
        Set<Integer> s1 = new HashSet<>(nums1);
        Set<Integer> s2 = new HashSet<>(nums2);
        // Set to store common elements between s1 and s2
        Set<Integer> common = new HashSet<>();

        elementsToRemove1 -= (n - s1.size());
        elementsToRemove2 -= (n - s2.size());

        // Find common elements between s1 and s2
        for (int x : s1) {
            if (s2.contains(x)) {
                common.add(x);
            }
        }

        // Keep removing elements till K elements are removed
        // from both the sets
        while (elementsToRemove1 > 0 || elementsToRemove2 > 0) {
            // If more elements are needed to be deleted from s1
            if (elementsToRemove1 > elementsToRemove2) {
                // If we are left with common elements, delete
                // them first
                if (!common.isEmpty()) {
                    int ele = common.iterator().next();
                    s1.remove(ele);
                    common.remove(ele);
                }
                // Else delete the unique elements
                else {
                    int ele = s1.iterator().next();
                    s1.remove(ele);
                }
                elementsToRemove1 -= 1;
            }
            // If more elements are needed to be deleted from s2
            else {
                // If we are left with common elements, delete
                // them first
                if (!common.isEmpty()) {
                    int ele = common.iterator().next();
                    s2.remove(ele);
                    common.remove(ele);
                }
                // Else delete the unique elements
                else {
                    int ele = s2.iterator().next();
                    s2.remove(ele);
                }
                elementsToRemove2 -= 1;
            }
        }
        return s1.size() + s2.size() - common.size();
    }

    // Driver Code
    public static void main(String[] args) {
        // Example input
        Vector<Integer> nums1 = new Vector<>(Set.of(1, 2, 3));
        Vector<Integer> nums2 = new Vector<>(Set.of(3, 4, 5));
        int k = 1;

        // Call the function and display the result
        int result = maximumSetSize(nums1, nums2, k);
        System.out.println("Output: " + result);
    }
}


// This code is contributed by rambabuguphka
C#
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    // Function to calculate the maximum size of a set with at
    // most k elements from nums1 and nums2
    static int MaximumSetSize(List<int> nums1, List<int> nums2, int k)
    {
        int n = nums1.Count;
        int elementsToRemove1 = k;
        int elementsToRemove2 = k;

        // Create hash sets to store unique elements from
        // nums1 and nums2
        HashSet<int> s1 = new HashSet<int>(nums1);
        HashSet<int> s2 = new HashSet<int>(nums2);
        // Set to store common elements between s1 and s2
        HashSet<int> common = new HashSet<int>(s1.Intersect(s2));

        elementsToRemove1 -= (n - s1.Count);
        elementsToRemove2 -= (n - s2.Count);

        // Keep removing elements till K elements are removed
        // from both the sets
        while (elementsToRemove1 > 0 || elementsToRemove2 > 0)
        {
            // If more elements are needed to be deleted from s1
            if (elementsToRemove1 > elementsToRemove2)
            {
                // If we are left with common elements, delete
                // them first
                if (common.Any())
                {
                    int ele = common.First();
                    s1.Remove(ele);
                    common.Remove(ele);
                }
                // Else delete the unique elements
                else
                {
                    int ele = s1.First();
                    s1.Remove(ele);
                }
                elementsToRemove1 -= 1;
            }
            // If more elements are needed to be deleted from s2
            else
            {
                // If we are left with common elements, delete
                // them first
                if (common.Any())
                {
                    int ele = common.First();
                    s2.Remove(ele);
                    common.Remove(ele);
                }
                // Else delete the unique elements
                else
                {
                    int ele = s2.First();
                    s2.Remove(ele);
                }
                elementsToRemove2 -= 1;
            }
        }
        return s1.Count + s2.Count - common.Count;
    }

    // Driver Code
    static void Main(string[] args)
    {
        // Example input
        List<int> nums1 = new List<int> { 1, 2, 3 };
        List<int> nums2 = new List<int> { 3, 4, 5 };
        int k = 1;

        // Call the function and display the result
        int result = MaximumSetSize(nums1, nums2, k);
        Console.WriteLine("Output: " + result);
    }
}
JavaScript
// Function to calculate the maximum size of a set with at
// most k elements from nums1 and nums2
function maximumSetSize(nums1, nums2, k) {
    let elementsToRemove1 = k;
    let elementsToRemove2 = k;

    // Create sets to store unique elements from nums1 and nums2
    let s1 = new Set(nums1);
    let s2 = new Set(nums2);
    // Set to store common elements between s1 and s2
    let common = new Set();

    elementsToRemove1 -= nums1.length - s1.size;
    elementsToRemove2 -= nums2.length - s2.size;

    // Find common elements between s1 and s2
    for (let x of s1) {
        if (s2.has(x)) {
            common.add(x);
        }
    }

    // Keep removing elements till K elements are removed
    // from both the sets
    while (elementsToRemove1 > 0 || elementsToRemove2 > 0) {
        // If more elements are needed to be deleted from s1
        if (elementsToRemove1 > elementsToRemove2) {
            // If we are left with common elements, delete
            // them first
            if (common.size > 0) {
                let ele = common.values().next().value;
                s1.delete(ele);
                common.delete(ele);
            }
            // Else delete the unique elements
            else {
                let ele = s1.values().next().value;
                s1.delete(ele);
            }
            elementsToRemove1 -= 1;
        }
        // If more elements are needed to be deleted from s2
        else {
            // If we are left with common elements, delete
            // them first
            if (common.size > 0) {
                let ele = common.values().next().value;
                s2.delete(ele);
                common.delete(ele);
            }
            // Else delete the unique elements
            else {
                let ele = s2.values().next().value;
                s2.delete(ele);
            }
            elementsToRemove2 -= 1;
        }
    }
    return s1.size + s2.size - common.size;
}

// Driver Code
let nums1 = [1, 2, 3];
let nums2 = [3, 4, 5];
let k = 1;

// Call the function and display the result
let result = maximumSetSize(nums1, nums2, k);
console.log("Output: " + result);
Python3
def maximum_set_size(nums1, nums2, k):
    n = len(nums1)
    elements_to_remove_1 = k
    elements_to_remove_2 = k

    # Create sets to store unique elements from nums1 and nums2
    s1 = set(nums1)
    s2 = set(nums2)
    # Set to store common elements between s1 and s2
    common = set()

    elements_to_remove_1 -= (n - len(s1))
    elements_to_remove_2 -= (n - len(s2))

    # Find common elements between s1 and s2
    for x in s1:
        if x in s2:
            common.add(x)

    # Keep removing elements till K elements are removed
    # from both the sets
    while elements_to_remove_1 > 0 or elements_to_remove_2 > 0:
        # If more elements are needed to be deleted from s1
        if elements_to_remove_1 > elements_to_remove_2:
            # If we are left with common elements, delete
            # them first
            if common:
                ele = common.pop()
                s1.remove(ele)
            # Else delete the unique elements
            else:
                ele = s1.pop()
            elements_to_remove_1 -= 1
        # If more elements are needed to be deleted from s2
        else:
            # If we are left with common elements, delete
            # them first
            if common:
                ele = common.pop()
                s2.remove(ele)
            # Else delete the unique elements
            else:
                ele = s2.pop()
            elements_to_remove_2 -= 1

    return len(s1) + len(s2) - len(common)


# Driver Code
if __name__ == "__main__":
    # Example input
    nums1 = [1, 2, 3]
    nums2 = [3, 4, 5]
    k = 1

    # Call the function and display the result
    result = maximum_set_size(nums1, nums2, k)
    print("Output:", result)

Output
Output: 4

Time Complexity: O(N), where N is the size of the input array nums1[] and nums2[].
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads