#1481

Least Number of Unique Integers after K Removals

Medium
ArrayHash TableGreedySortingCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach leverages frequency counting and sorting. By removing the least frequent integers first, we minimize the number of unique integers remaining after k removals.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the frequency of each integer in the array using a HashMap.
  2. 2Step 2: Sort the integers based on their frequency in ascending order.
  3. 3Step 3: Remove integers starting from the least frequent until k removals are made.
  4. 4Step 4: Count the remaining unique integers.
solution.py14 lines
1# Full working Python code
2from collections import Counter
3
4def least_num_unique_ints(arr, k):
5    freq = Counter(arr)
6    unique_count = len(freq)
7    freq_values = sorted(freq.values())
8    for count in freq_values:
9        if k >= count:
10            k -= count
11            unique_count -= 1
12        else:
13            break
14    return unique_count

Complexity note: The time complexity is dominated by the sorting step, which is O(n log n), while the space complexity is O(n) due to the storage of frequency counts.

  • 1Removing the least frequent integers first minimizes the unique count.
  • 2Using a frequency map helps efficiently track and manage counts.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.