Duplicate Elements in Array in Java

(Last Updated On: 13/10/2023)

In this blog, we will delve into identifying and handling duplicate elements in arrays using Java, ensuring a comprehensive understanding of this crucial concept.

In the world of programming, arrays are versatile data structures used to store a collection of elements. While arrays offer efficient data management, they can also present challenges, one of which is the presence of duplicate elements. Handling duplicates is essential for accurate data processing, analysis, and maintaining the integrity of information.

Identifying Duplicate Elements in Array in Java 

The Problem Statement

Imagine you have an array with multiple elements, and you need to identify and print the duplicate values. The goal is to ensure that each duplicate value is displayed only once in the output, providing a clear and concise representation of the data.

Approaches to Identify Duplicate Elements in Array in Java

Using Nested Loops

One approach to identify duplicate elements in an array in Java is by using nested loops. Additionally, For each element in the array, we can compare it with every other element to check for duplicates. While this method is straightforward, it may not be the most efficient for large arrays.

public class IdentifyDuplicatesNestedLoops {
    public static void main(String[] args) {
        int[] arr = { 5, 2, 7, 2, 8, 7, 1, 9, 5 };

        System.out.println("Original Array:");
        for (int num : arr) {
            System.out.print(num + " ");
        }

        System.out.println("\n\nDuplicate Elements:");
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    System.out.println(arr[i]);
                }
            }
        }
    }
}

Explanation of the code:

In the code above, we first initialize an array `arr` with some elements. We then iterate through the array using nested loops. The outer loop runs from index 0 to the second-to-last index, and the inner loop runs from the next index (i + 1) to the last index.

Inside the inner loop, we compare the elements at positions `arr[i]` and `arr[j]`. If they are equal, indicating that we have found a duplicate element, then we print it to the console.

In this example, the output shows that the duplicate elements in the array are 5, 2, and 7. Keep in mind that this approach has a time complexity of O(n^2), however, which may not be efficient for large arrays.

Output:

Original Array:
5 2 7 2 8 7 1 9 5 

Duplicate Elements:
5
2
7

Utilizing a HashSet

A more efficient approach, therefore, involves utilizing a HashSet, which is a data structure that stores unique elements. By iterating through the array and adding each element to the HashSet, we can effectively identify duplicate elements in the array in Java based on whether the element is already present in the set.

import java.util.*;

public class IdentifyDuplicatesUsingHashSet {
    public static void main(String[] args) {
        int[] arr = { 4, 7, 2, 9, 4, 8, 3, 7, 1, 6 };

        Set<Integer> uniqueElements = new HashSet<>();
        Set<Integer> duplicates = new HashSet<>();

        System.out.println("Array elements:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println("\n");

        System.out.println("Duplicate elements:");
        for (int num : arr) {
            if (!uniqueElements.add(num)) {
                duplicates.add(num);
            }
        }

        for (int duplicate : duplicates) {
            System.out.print(duplicate + " ");
        }
    }
}

Explanation of the code:

In this code, furthermore, we define an array ‘arr’ with some integer elements. We use two HashSets: `uniqueElements` to keep track of unique elements encountered, and `duplicates` to store the duplicate elements found.

We then iterate through the array using a for-each loop. For each element, we check if it can be added to the `uniqueElements` set. If it cannot be added (i.e., it’s a duplicate), we add it to the `duplicates` set.

Finally, we iterate through the `duplicates` set and print the duplicate elements found in the array.

In the provided example, the array contains the elements ‘{4, 7, 2, 9, 4, 8, 3, 7, 1, 6}’. Additionally, the output correctly identifies the duplicate elements as ‘4’ and ‘7’.

Output:

Array elements:
4 7 2 9 4 8 3 7 1 6 

Duplicate elements:
4 7

Displaying Duplicate Values Only Once

The provided Java code intends to identify and print duplicate elements in a Java Array, ensuring that the output displays each duplicate value only once.

Get a Complete list of Online Certification Courses in India here!

// Duplicate Elements in Array in Java

import java.util.ArrayList;
public class duplicateElementEx {

// Function to find the Duplicates,if duplicate occurs 2 times or more than 2 times in array so, it will print duplicate value only once at output
	static void findDuplicate(int arr[], int len)
	{
		// initialize ifPresent as false
		boolean ifPresent = false;
		// ArrayList to store the output
		ArrayList<Integer> a = new ArrayList<Integer>();
		for (int i = 0; i < len - 1; i++) {
			for (int j = i + 1; j < len; j++) {
				if (arr[i] == arr[j]) {					
// checking if element is present in the ArrayList or not if present then break
					if (a.contains(arr[i])) {
						break;
					}
// if element is not present in the ArrayList then add it to ArrayList and make ifPresent at true
					else {
						a.add(arr[i]);
						ifPresent = true;
					}
				}
			}
		}

		// if duplicates is present then print ArrayList
		if (ifPresent == true) {
			System.out.print(a + " ");
		}
		else {
			System.out.print("No duplicates present in arrays");
		}
	}
	// Driver Code
	public static void main(String[] args)
	{

		int arr[] = { 1, 11, 4, 1, 8, 4, 1, 12, 11 };
		int n = arr.length;
		findDuplicate(arr, n);
	}
}

Explanation of the code:
The program utilizes an ArrayList to store, moreover, the duplicate elements found in the array. Let’s take a closer look at how the code functions:

1. The function `findDuplicate` is defined with two parameters: an integer array `arr` and its length `len`.

2. Additionally, an ArrayList ‘a’ is initialized to store the duplicate elements found in the array.

3. The code uses nested loops to compare each element in the array with all subsequent elements, thereby finding duplicates. If a duplicate is found, the code checks if the element is already existing in the ArrayList ‘a’.

4. If the element is not present in the ArrayList, then it is added to the ArrayList, and the `ifPresent` flag is set to `true`.

5. If duplicates are present (i.e., `ifPresent` is `true`), the ArrayList `a` containing the unique duplicate elements is printed. If no duplicates are found, the message “No duplicates present in arrays” is printed.

6. In the `main` function, an integer array `arr` is initialized with values: `{1, 11, 4, 1, 8, 4, 1, 12, 11}`.

7. The `findDuplicate` function is called with the array `arr` and its length `n`.

8. Finally the function `findDuplicate` processes the array and prints the unique duplicate elements found in the array.

In the given example, the array contains duplicate elements: `1`, `4`, and `11`. The output of the code will be: `[1, 4, 11]`, which corresponds to the unique duplicate elements found in the array. The code makes sure to display each duplicate value in the output only once.

Output:

[1, 11, 4] 

Learn How to Generate Random Numbers in Javascript, Now!

Array for binary search function

Below Java code is designed to identify and print duplicate elements in array in java using a binary search-based approach.

// Duplicate Elements in Array in Java
import java.io.*;
import java.util.*;
class duplicateElementsEx {
	// Function to find lower bound of target in arr
	public static int lowerBound(int[] arr, int target)
	{
		int low = 0, hig = arr.length - 1;
		int ans = -1;
		while (low <= hig) {
			int mid = low + (hig - low) / 2;
			if (arr[mid] >= target) {
				ans = mid;
				hig = mid - 1;
			}
			else {
				low = mid + 1;
			}
		}
		return ans;
	}

	// Function to find upper bound of target in arr
	public static int upperBound(int[] arr, int target)
	{
		int low = 0, hig = arr.length - 1;
		int ans = -1;
		while (low <= hig) {
			int mid = low + (hig - low) / 2;
			if (arr[mid] <= target) {
				ans = mid;
				low = mid + 1;
			}
			else {
				hig = mid - 1;
			}
		}
		return ans;
	}

	// Function to print elements that occur more than once
	// in arr
	static void printDuplicates(int[] arr, int n)
	{
		Arrays.sort(arr); // sort array for binary search

		System.out.print("[");
		for (int i = 0; i < n; i++) {
			// index of first and last occ of arr[i]
			int firstIndex = lowerBound(arr, arr[i]);
			int lastIndex = upperBound(arr, arr[i]);

			int occurTime = lastIndex - firstIndex
							+ 1; // frequency of arr[i]

			if (occurTime
				> 1) { // elements that occur more than 1
				i = lastIndex; // update i to last_index
				System.out.print(arr[i] + ", ");
			}
		}
		System.out.println("]");
	}

	public static void main(String[] args)
	{
		int[] arr = { 1, 14, 4, 16, 4, 1, 5, 16, 56 };
		int n = arr.length;

		// Function call
		printDuplicates(arr, n);
	}
}

Explanation of the code:

The objective is to efficiently determine elements that occur more than once in the array and then print them.

1. The binary search utilizes the ‘lowerBound’ and ‘upperBound’ functions. The `lowerBound` function calculates the index of the first occurrence of a target element within the array, while the `upperBound` function calculates the index of the last occurrence of the target element. These functions help determine the frequency of each element in the array.

2. The `printDuplicates` function is responsible for iterating through the sorted array, identifying elements that occur more than once, and printing them. It uses the `lowerBound` and `upperBound` functions to calculate the frequency of each element and determine if it occurs more than once. If the frequency of an element is greater than 1, the system considers it a duplicate and prints it.

3. In the `main` function, an example array `arr` is defined, containing elements `{1, 14, 4, 16, 4, 1, 5, 16, 56}`. The ‘printDuplicates’ function calls for this array and its length ‘n’, thereby resulting in identifying and printing duplicate elements.

4.In Java, the code utilizes a binary search-based approach to efficiently discover duplicate elements in an array. It demonstrates the optimization of the process by leveraging lower and upper bounds. Please note that you must sort the array before executing the duplicate identification method based on binary search.

Output:

[1, 4, 16, ]

10 Tips and Tricks for identification of duplication elements in an array in Java.

Check out 10 tips and tricks for effectively implementing the identification of duplicate elements in array in Java are as follows:

1. Sort the Array: 

Before identifying duplicate elements, it’s essential to sort the array. Sorting the array allows for efficient comparison of adjacent elements and simplifies the duplicate identification process.

2. Utilize Binary Search: 

Binary search can significantly enhance the efficiency of duplicate identification, especially for sorted arrays. Implement binary search algorithms to find the lower and upper bounds of elements.

3. Choose Appropriate Data Structures: 

Consider using data structures like HashSet or HashMap to efficiently track and count occurrences of elements. Moreover, these structures offer constant time complexity for operations, making duplicate detection faster.

Learn How to find Square Root of a Number in Java Now!

4. Use Streams: 

Java Streams provide concise and expressive ways to process arrays. By converting the array into a Stream, you can then leverage various stream operations to identify and manipulate duplicates effectively.

5. Keep Code Modular: 

Break down your code into modular functions or methods. This enhances readability and maintainability, allowing you to focus on specific tasks such as sorting, binary search, or duplicate identification.

6. Optimize for Large Arrays: 

For large arrays, memory efficiency is crucial. Opt for algorithms that minimize memory usage; furthermore, consider using bit manipulation techniques for space optimization.

7. Consider Time Complexity: 

Different approaches have varying time complexities. Analyze the time complexity of your chosen method and consider factors such as the array size and expected duplicate count.

8. Handle Edge Cases: 

Account for edge cases, such as empty arrays or arrays with no duplicates, in your implementation. Properly handling edge cases ensures the robustness of your solution.

9. Use Test Cases: 

Create test cases with known arrays and then duplicates to validate your implementation. Testing helps identify bugs and ensures your code functions as intended.

10. Document Your Code: 

Provide clear comments and documentation explaining the logic and purpose of each step. Well-documented code is easier to understand, maintain, and troubleshoot.

By following these tips and tricks, you can efficiently and effectively implement the identification of duplicate elements in array in Java, improving the performance and reliability of your code.

Practical Application: Duplicate Handling in Real Scenarios

Duplicate elements in array in Java have real-world implications across various scenarios, highlighting their crucial significance:

Data Validation in Forms

When users submit data through forms, it’s crucial to validate and eliminate duplicate entries. Whether it’s user registrations, survey responses, or feedback submissions, duplicate handling ensures accurate and reliable data collection.

Counting Occurrences

In scenarios where you need to count the occurrences of specific elements, duplicates can skew the results. Proper handling ensures accurate frequency counts, whether it’s analyzing user preferences, survey responses, or product sales.

Database Operations

Databases store vast amounts of information, and duplicates can lead to data redundancy and inefficiency. By handling duplicates during data insertion or retrieval, databases can maintain clean and organized records.

In this blog, we learn that understanding and effectively managing duplicate elements in arrays is a crucial skill in Java programming. By exploring various approaches, applying best practices, and then considering practical applications, developers can enhance their problem-solving abilities and create more efficient and reliable code.

We believe our discussion on ‘Duplicate Elements in Array in Java’ has provided valuable insights. Keep check for more updates and programming blogs by visiting our Newtum website. Also explore our various courses such as PHP, C Programming for kids, and Happy coding!

About The Author

Leave a Reply