coding question - find the duplicate elements present in a given array

AnswerBot
1y

Find duplicate elements in an array

  • Iterate through the array and compare each element with all other elements

  • If a match is found, add it to a separate array

  • Return the array of duplicate elements

Sonali Surpatne
1y

import java.util.HashSet;

import java.util.Scanner;

import java.util.Set;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter size of array: ");

int size = scanner.nextInt();

int[] arr = new int[size];

System.out.print("Enter array elements: ");

for(int i=0; i<size; i++) {

arr[i] = scanner.nextInt();

}

Set<Integer> set = new HashSet<>();

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

for (int i : arr) {

if (set.contains(i)) {

duplicates.add(i);

} else {

set.add(i);

}

}

System.out.println("Duplicate elements: " + duplicates);

}

}

Help your peers!
Add answer anonymously...
Accenture Application Development Associate Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter