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

You are given an integer array nums. You need to ensure that the elements in the array are distinct.

To achieve this, you can perform the following operation any number of times:

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

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

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

Input & Output

Example 1 — Duplicate Elements
$ Input: nums = [1,2,1,3,4]
Output: 1
💡 Note: Elements 1 appears twice. Remove first 3 elements [1,2,1], leaving [3,4] which are distinct. One operation needed.
Example 2 — Already Distinct
$ Input: nums = [1,2,3,4]
Output: 0
💡 Note: All elements are already distinct, so no operations needed.
Example 3 — Small Array with Duplicates
$ Input: nums = [1,1]
Output: 1
💡 Note: Two duplicate 1s. Since array has less than 3 elements, remove all in one operation.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Minimum Operations to Make Array DistinctInput Array:12134← Duplicates: 1 appears twiceOperation 1: Remove First 3 Elements34← All distinct!Result Array:[3, 4]Distinct elements onlyKey Insight• We can only remove from the beginning• Each operation removes exactly 3 elements (or all remaining if < 3)• Find rightmost duplicate position• Calculate: ⌈(position + 1) / 3⌉• Example: position 2 → ⌈3/3⌉ = 1 opOutput: 1 operation needed
Understanding the Visualization
1
Input Array
Array with duplicate elements that need to be eliminated
2
Remove Operations
Remove 3 elements at a time from the beginning until distinct
3
Result
Return minimum operations needed
Key Takeaway
🎯 Key Insight: Work backwards to find the rightmost duplicate, then calculate how many 3-element removals are needed
Asked in
Meta 8 Google 6 Amazon 4
12.4K Views
Medium Frequency
~15 min Avg. Time
245 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