Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug #4520

Closed
wafula204 opened this issue Feb 16, 2025 · 0 comments
Closed

bug #4520

wafula204 opened this issue Feb 16, 2025 · 0 comments

Comments

@wafula204
Copy link

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;
}

}

@microsoft-github-policy-service microsoft-github-policy-service bot added the Needs-Triage 🔍 It's a new issue that core contributor team needs to triage. label Feb 16, 2025
@microsoft-github-policy-service microsoft-github-policy-service bot removed the Needs-Triage 🔍 It's a new issue that core contributor team needs to triage. label Feb 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants