Least Number of Unique Integers after K Removals - Problem

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

You need to remove exactly k elements from the array, and your goal is to minimize the number of distinct integers that remain.

Strategy: To minimize unique integers, remove elements with the lowest frequencies first, as this eliminates entire unique values faster than removing high-frequency elements.

Input & Output

Example 1 — Basic Case
$ Input: arr = [4,3,1,1,3], k = 2
Output: 2
💡 Note: Count frequencies: 4 appears 1 time, 3 appears 2 times, 1 appears 2 times. Remove the element with frequency 1 (value 4) using 1 removal. We have 1 more removal left but can't eliminate any complete group. Result: 2 unique values remain (3 and 1).
Example 2 — Complete Elimination
$ Input: arr = [5,5,4], k = 2
Output: 1
💡 Note: Count frequencies: 5 appears 2 times, 4 appears 1 time. Remove value 4 (1 removal), then remove one instance of 5 (1 more removal). We used 2 removals total. Result: 1 unique value remains (5).
Example 3 — Minimum Input
$ Input: arr = [1], k = 1
Output: 0
💡 Note: Only one element exists with frequency 1. Remove it completely using 1 removal. Result: 0 unique values remain.

Constraints

  • 1 ≤ arr.length ≤ 105
  • 1 ≤ arr[i] ≤ 109
  • 1 ≤ k ≤ arr.length

Visualization

Tap to expand
Least Number of Unique Integers after K Removals INPUT Array arr: 4 3 1 1 3 [0] [1] [2] [3] [4] k = 2 Frequency Count: Value Frequency 4 1 3 2 1 2 ALGORITHM STEPS 1 Count Frequencies Build freq map for each value 2 Sort by Frequency Ascending order: [1, 2, 2] 1 2 2 (freqs) 3 Remove Greedily Remove lowest freq first k=2, freq=1: remove 4 k=2-1=1, remaining=1 (Cannot fully remove freq=2) 4 Count Remaining Unique values left: 3, 1 Remaining unique: 2 FINAL RESULT After removing k=2 elements: Removed: one '4', one '3' or '1' Remaining Array Example: 3 1 1 Unique values remaining: 3 1 OUTPUT 2 OK Key Insight: Greedy approach: Always remove elements with the lowest frequency first. This allows us to eliminate entire unique values with fewer removals, minimizing the count of distinct integers remaining. TutorialsPoint - Least Number of Unique Integers after K Removals | Greedy Approach
Asked in
Amazon 15 Facebook 8 Google 6
28.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen