LeetCode 3396: Minimum Number of Operations to Make Elements in Array Distinct Solution

Master LeetCode problem 3396 (Minimum Number of Operations to Make Elements in Array Distinct), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

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

Problem Explanation

Explanation

To solve this problem, we can iterate through the array and maintain a set to keep track of the elements we have seen so far. For each element, if it is already in the set, we increment our operations count by 1. If it is not in the set, we add it to the set. Whenever the size of the set reaches 3, we clear the set and increment the operations count by 1.

The time complexity of this approach is O(N) where N is the number of elements in the input array. The space complexity is O(1) since the set will contain at most 3 elements.

Solution Code

import java.util.HashSet;
import java.util.Set;

class Solution {
    public int minOperations(int[] nums) {
        Set<Integer> set = new HashSet<>();
        int operations = 0;

        for (int num : nums) {
            if (set.contains(num)) {
                operations++;
            } else {
                set.add(num);
            }

            if (set.size() == 3) {
                set.clear();
                operations++;
            }
        }

        return operations;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3396 (Minimum Number of Operations to Make Elements in Array Distinct)?

This page provides optimized solutions for LeetCode problem 3396 (Minimum Number of Operations to Make Elements in Array Distinct) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3396 (Minimum Number of Operations to Make Elements in Array Distinct)?

The time complexity for LeetCode 3396 (Minimum Number of Operations to Make Elements in Array Distinct) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3396 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3396 in Java, C++, or Python.

Back to LeetCode Solutions