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 for Distinct Elements INPUT nums = [1, 2, 1, 3, 4] 1 [0] 2 [1] 1 [2] 3 [3] 4 [4] Duplicate Found: 1 at index 0 and 2 Hash Map State 1 --> [0, 2] (dup!) 2 --> [1] 3 --> [3] 4 --> [4] ALGORITHM STEPS 1 Scan from End Find first duplicate 2 Build Hash Map Track element indices 3 Find Remove Point Index of dup to remove 4 Calculate Operations ceil((idx + 1) / 3) Remove First 3 Elements 1 2 1 3 4 After: [3, 4] - All distinct! FINAL RESULT Operations Needed: 1 Resulting Array: 3 4 OK All elements distinct Calculation: First dup at idx 2 ceil((2 + 1) / 3) = 1 op Key Insight: Use a Hash Map to scan from the end of the array. Find the first index where a duplicate occurs (earlier element matching a later one). The number of operations = ceil((index + 1) / 3). TutorialsPoint - Minimum Number of Operations to Make Elements in Array Distinct | Hash Map Optimization
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