Taro Logo

Least Number of Unique Integers after K Removals

#2 Most AskedMedium
1 view
Topics:
ArraysGreedy Algorithms

Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.

Example 1:

Input: arr = [5,5,4], k = 1
Output: 1
Explanation: Remove the single 4, only 5 is left.
Example 2:
Input: arr = [4,3,1,1,3,3,2], k = 3
Output: 2
Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.

Constraints:

  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 10^9
  • 0 <= k <= arr.length

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements in the input array (e.g., can they be negative, zero, or very large)?
  2. Can $k$ be larger than the total number of elements in the array, or larger than the number of unique integers?
  3. If $k$ is larger than needed to remove all unique elements, should the result be 0?
  4. Should we always remove entire groups of identical elements, or can we remove just a subset of occurrences of a specific integer?
  5. What should be returned if the input array is empty or $k$ is 0?

Brute Force Solution

Approach

Imagine you have a collection of different numbered items and you are allowed to throw away a specific number of them. The brute force approach involves trying every single possible combination of items to throw away, and for each choice, counting how many different types of numbers are left over.

Here's how the algorithm would work step-by-step:

  1. Start by looking at all the items you currently have and identify how many times each different number appears.
  2. Imagine every possible way to pick a set number of items to throw away into the trash.
  3. For the first possibility, remove that chosen set of items from your collection.
  4. Count how many unique numbers are still left sitting on the table.
  5. Write down that count and remember the choice you made.
  6. Put the thrown-away items back, and now choose a completely different set of items to throw away.
  7. Repeat this exact process of throwing away, counting, and resetting for every single possible combination of items you could choose to remove.
  8. Once you have checked every combination, look back at all your written counts and find the smallest one.
  9. Declare that smallest count as the final answer.

Code Implementation

import itertools


def find_least_unique_integers(arr, removals_allowed):
    # We generate all combinations of elements to remove in order to explore every possible scenario.
    all_possible_removals = list(itertools.combinations(arr, removals_allowed))
    
    minimum_unique_count = len(set(arr))
    
    for removal_combination in all_possible_removals:
        remaining_elements = list(arr)
        for item_to_remove in removal_combination:
            remaining_elements.remove(item_to_remove)
            
        # Evaluating the unique count for each combination allows us to track the absolute minimum left over.
        current_unique_count = len(set(remaining_elements))
        if current_unique_count < minimum_unique_count:
            minimum_unique_count = current_unique_count
            
    return minimum_unique_count

Big(O) Analysis

Time Complexity
O(2^n) – To find the least number of unique integers, the brute force approach evaluates every possible combination of items to remove from the collection of n elements. Generating and testing all subsets of items results in an exponential number of choices, specifically 2 to the power of n possibilities. For each of these 2^n combinations, we must recount the remaining unique items. This leads to approximately 2^n operations, which simplifies in Big O notation to O(2^n).
Space Complexity
O(U) – To analyze the auxiliary space, let N be the total number of items in the collection and U be the number of unique integers. Step 1 requires a frequency map or hash table to store each unique integer and its count, taking O(U) space. We then extract these frequencies into a list or min-heap to sort them, which also requires O(U) auxiliary space. Therefore, the extra memory used scales linearly with the number of unique integers rather than the total number of items.

Optimal Solution

Approach

To find the fewest number of unique integers after removing a certain number of elements, we should get rid of the numbers that appear least often first. By targeting the rarest items entirely, we make the most efficient use of our removals and eliminate as many distinct values as possible.

Here's how the algorithm would work step-by-step:

  1. Count how many times each different number appears in the collection.
  2. Sort these frequency counts from the smallest to the largest so we know which numbers are the rarest.
  3. Go through the sorted counts one by one, starting with the least frequent numbers.
  4. For each number group, subtract its count from your allowed budget of removals.
  5. If you have enough budget to completely wipe out all instances of that number, do so and move on to the next rarest number.
  6. If your remaining budget is not enough to completely wipe out the current number group, stop removing because you cannot clear out any more unique numbers.
  7. Count how many unique numbers are left over after your budget runs out, and report that as the final answer.

Code Implementation

from collections import Counter


def find_least_num_of_unique_ints(arr, removals):
    # Counting frequencies allows us to identify and target the rarest integers first.
    frequency_counts = Counter(arr)
    
    sorted_frequencies = sorted(frequency_counts.values())
    
    unique_integer_count = len(sorted_frequencies)
    
    for frequency in sorted_frequencies:
        # We stop when remaining removals cannot fully eliminate the next rarest number group.
        if removals >= frequency:
            removals -= frequency
            unique_integer_count -= 1
        else:
            break
            
    return unique_integer_count

Big(O) Analysis

Time Complexity
O(n log n) – Counting the frequency of each element in the input array of size n requires a single pass, which takes O(n) time. Next, extracting these unique frequencies and sorting them takes O(u log u) time, where u represents the number of unique integers and u is at most n. Iterating through the sorted frequencies to deplete the budget of removals takes at most O(u) time in the worst case. Since sorting dominates the operations, the total time complexity is driven by O(n log n) operations from the sorting step.
Space Complexity
O(u) – The auxiliary space is driven by the frequency map and the list of counts, where u is the number of unique integers in the input. In the worst case where every element is distinct, u equals N, making the auxiliary memory scale linearly with the input size N. Specifically, the hash map stores up to N frequency pairs, and the sorting step maintains a list or array proportional to the number of unique elements.

Edge Cases

K is greater than or equal to the total number of elements in the array
How to Handle:
The greedy removal of lowest frequencies will exhaust all elements, resulting in zero unique integers left.
K is zero, meaning no elements are removed
How to Handle:
The algorithm skips removal entirely and simply returns the initial count of unique integers in the frequency map.
All elements in the array are identical
How to Handle:
The frequency map will contain a single entry, and subtracting K from its count will either leave 1 unique integer or 0 if K is greater than or equal to the array length.
All elements in the array are unique
How to Handle:
Every element has a frequency of one, so removing K elements will simply reduce the number of unique integers by K.
Array contains negative numbers, zeros, and positive numbers
How to Handle:
Using a hash map for frequency counting naturally accommodates any integer values as keys without requiring normalization.
Multiple elements share the exact same frequency
How to Handle:
Sorting the frequencies ensures we greedily eliminate whichever elements have the smallest counts first, regardless of their actual value.
K is large enough to partially remove elements of a specific frequency group
How to Handle:
The greedy loop checks if remaining K is less than the current frequency and breaks out early since we cannot fully remove that group.
Extremely large inputs reaching maximum constraint limits
How to Handle:
Using an efficient O(N log N) sorting approach on unique frequencies ensures the solution executes well within standard time limits.
0/2 completed