Closed
Description
import java.util.HashSet;
import java.util.Arrays;
public class DuplicateChecker {
public static boolean hasDuplicates(int[] arr) {
// Use a HashSet to efficiently detect duplicates. HashSets don't allow duplicates.
HashSet<Integer> seen = new HashSet<>();
for (int num : arr) {
if (seen.contains(num)) {
return true; // Found a duplicate!
}
seen.add(num); // Add the current number to the set.
}
return false; // No duplicates found after checking all elements.
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {1, 2, 3, 2, 5};
int[] arr3 = {1,1,1,1,1};
int[] arr4 = {}; //Empty array
System.out.println("Array 1 has duplicates: " + hasDuplicates(arr1)); // Output: false
System.out.println("Array 2 has duplicates: " + hasDuplicates(arr2)); // Output: true
System.out.println("Array 3 has duplicates: " + hasDuplicates(arr3)); // Output: true
System.out.println("Array 4 has duplicates: " + hasDuplicates(arr4)); // Output: false (an empty array has no duplicates)
//Demonstrating with other data types (example with Strings):
String[] strArr1 = {"apple", "banana", "cherry"};
String[] strArr2 = {"apple", "banana", "apple"};
System.out.println("String Array 1 has duplicates: " + hasDuplicates(strArr1)); // Output: false
System.out.println("String Array 2 has duplicates: " + hasDuplicates(strArr2)); // Output: true
}
//Overloading the hasDuplicates method to work with other data types (e.g., String)
public static boolean hasDuplicates(String[] arr) {
HashSet<String> seen = new HashSet<>();
for (String str : arr) {
if (seen.contains(str)) {
return true;
}
seen.add(str);
}
return false;
}
}
Metadata
Metadata
Assignees
Labels
No labels