DDSA Solutions

3396. Minimum Number of Operations to Make Elements in Array Distinct

Time: O(n)
Space: O(n)
Advertisement

Intuition

Minimum operations to make values <= k. Same as 3375 essentially.

Algorithm

  1. 1Count distinct values > k. If any value < k that cannot be changed: -1.

Common Pitfalls

  • Each distinct value > k requires one operation (set-to-k op).
3396.cs
C#
// Approach: Scan from right in groups of 3; stop when first duplicate encountered; ops = ceil remaining.
// Time: O(n) Space: O(n)

public class Solution
{
    public int MinimumOperations(int[] nums)
    {
        var set = new HashSet<int>();
        for (int i = nums.Length - 1; i >= 0; i--)
        {
            if (!set.Add(nums[i]))
                return (i + 1 + 2) / 3;
        }

        return 0;
    }
}
Advertisement
Was this solution helpful?