Minimum Number of Operations to Make Elements in Array Distinct - Problem

You are given an integer array nums that may contain duplicate elements. Your goal is to make all elements in the array distinct by performing a special removal operation.

In each operation, you can:

  • Remove exactly 3 elements from the beginning of the array
  • If the array has fewer than 3 elements remaining, remove all remaining elements

Note: An empty array is considered to have distinct elements.

Return the minimum number of operations needed to make all elements in the array distinct.

Example: If nums = [1, 2, 3, 1, 2], we have duplicates (1 and 2 appear twice). We need to remove elements from the front until no duplicates remain.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 2, 3, 1, 2]
โ€บ Output: 2
๐Ÿ’ก Note: We have duplicates: 1 appears at positions 0 and 3, 2 appears at positions 1 and 4. After 1 operation (removing first 3 elements), we have [1, 2] which still has the duplicates from the original array. After 2 operations (removing all elements), we have an empty array which is considered distinct.
example_2.py โ€” Already Distinct
$ Input: [1, 2, 3, 4]
โ€บ Output: 0
๐Ÿ’ก Note: All elements are already distinct, so no operations are needed.
example_3.py โ€” Single Element
$ Input: [5]
โ€บ Output: 0
๐Ÿ’ก Note: A single element array is always distinct, so 0 operations are needed.

Constraints

  • 0 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 105
  • You can only remove elements from the beginning of the array
  • Each operation removes exactly 3 elements (or all remaining if < 3)

Visualization

Tap to expand
๐Ÿ“š Library Book Organization AnalogyProblem: Remove books from LEFT only, 3 at a timeBook ABook BBook CBook ABook DSolution: Find rightmost position where suffix is uniqueBook ABook DMust remove these 4 booksOperations needed: ceil(4/3) = 2๐ŸŽฏ Key InsightInstead of simulating book removal operations,find the rightmost starting point where all remaining books are unique!
Understanding the Visualization
1
Identify the Goal
We need all remaining books to be unique (no duplicate titles)
2
Work Backwards
Instead of simulating removals, find the rightmost position where all books to the right are unique
3
Calculate Operations
Once we know how many books to remove from the left, divide by 3 (rounding up) to get operations needed
Key Takeaway
๐ŸŽฏ Key Insight: Work backwards to find the rightmost position where the suffix contains only distinct elements, then calculate the minimum operations needed to remove everything to the left of that position.
Asked in
Google 25 Amazon 20 Meta 15 Microsoft 12
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