
Java Programming
May 23, 2025 at 01:05 PM
*Java Coding Challenge: Part 10 – Find Duplicates in an Array*
*Challenge: Write a Java program to find duplicate elements in an array without using Set or Map.*
*Example:*
Input: {4, 2, 7, 2, 4, 9}
Output:
Duplicates: 2, 4
*Approach:*
- Use a nested loop to compare each element with the rest.
- Use a visited boolean array to avoid printing the same duplicate multiple times.
*Java Code:*
public class FindDuplicates {
public static void main(String[] args) {
int[] arr = {4, 2, 7, 2, 4, 9};
boolean[] visited = new boolean[arr.length];
System.out.print("Duplicates: ");
for (int i = 0; i < arr.length; i++) {
if (visited[i]) continue;
boolean isDuplicate = false;
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
visited[j] = true;
isDuplicate = true;
}
}
if (isDuplicate) {
System.out.print(arr[i] + " ");
}
}
}
}
*This approach is simple but has O(n²) time complexity.*
*You can mention this in interviews and suggest using HashSet for better efficiency if allowed.*
*React ❤️ for Part-11*
❤️
❤
👍
♥
🙏
💣
🗿
😂
😍
😞
62