Magicsheet logo

Least Number of Unique Integers after K Removals

Medium
53.3%
Updated 6/1/2025

Least Number of Unique Integers after K Removals

What is this problem about?

The "Least Number of Unique Integers after K Removals interview question" involves an array of integers and an integer k. You are tasked with removing exactly k elements from the array such that the number of unique integers remaining in the array is minimized. This "Least Number of Unique Integers after K Removals coding problem" requires a strategic approach to decide which elements to remove first to achieve the goal of reducing the count of unique values.

Why is this asked in interviews?

This problem is a favorite for testing "Greedy interview pattern" and "Hash Table interview pattern" skills. It forces candidates to think about frequency counts and how removing elements with lower frequencies first is more beneficial for reducing the total number of unique items. It's a great way to see if a candidate can optimize for a specific metric (unique count) under a constraint (number of removals).

Algorithmic pattern used

The strategy is Greedy. First, use a Hash Map to count the frequency of each integer in the array. Then, sort these frequencies in ascending order. To minimize the number of unique integers, you should start removing elements that appear the least often. By removing all instances of a low-frequency number, you completely eliminate one unique integer from the count. You continue this until you've used up your k removals.

Example explanation

Consider the array [4, 3, 1, 1, 3, 3, 2] and k = 3.

  1. Count Frequencies: {4: 1, 2: 1, 1: 2, 3: 3}.
  2. Sort Frequencies: 1 (from 4), 1 (from 2), 2 (from 1), 3 (from 3).
  3. Process Removals:
    • Remove the number '4' (freq 1). Removals left: 3 - 1 = 2. Unique count reduced by 1.
    • Remove the number '2' (freq 1). Removals left: 2 - 1 = 1. Unique count reduced by 1.
    • Next is frequency 2 (from number 1). We only have 1 removal left, which isn't enough to remove all '1's. So we stop. Remaining unique integers: 2 (the numbers '1' and '3').

Common mistakes candidates make

  • Removing high-frequency items: Thinking that removing the most common numbers will help more, which is the opposite of the correct strategy.
  • Incomplete removals: Forgetting that a unique integer only disappears if all its occurrences are removed.
  • Sorting the array instead of frequencies: Sorting the entire array can be slower than just sorting the unique counts.

Interview preparation tip

Always look for the "Greedy" angle in optimization problems. If you need to minimize or maximize something by making a series of choices, ask yourself if picking the "best" option at each step (like the lowest frequency here) leads to the global optimum.

Similar Questions