Sobes.tech
Middle+

How would you check if there are duplicates in an array of 1 million numbers?

sobes.tech AI

Answer from AI

To check for duplicates in an array of 1 million numbers in Java, you can use HashSet for efficient duplicate detection:

import java.util.HashSet;

public boolean hasDuplicates(int[] arr) {
    HashSet<Integer> seen = new HashSet<>();
    for (int num : arr) {
        if (!seen.add(num)) { // add returns false if the element already exists
            return true; // duplicate found
        }
    }
    return false; // no duplicates
}

This method has a time complexity of O(n) and a space complexity of O(n), which is acceptable for a million elements. If memory is limited, you can sort the array and check neighboring elements for equality, but sorting will be O(n log n).