How to Find Duplicates Elements in Java Array? - Java Interview Questions -5

preview_player
Показать описание
How to Find Duplicates Elements in Java Array: The most important interview question.

Solution 1 : with Time Complexity = O(nxn)

Our first solution is very simple. All we are doing here is to loop over an array and comparing each element to every other element. Since we are comparing every element to every other element, this solution has quadratic time complexity i.e. O(n^2). This solution has the worst complexity in all three solutions.

======================================================

Solution 2 : with Time Complexity = O(n)

Second solution is even simpler than this. All you need to know is that Set doesn't allow duplicates in Java. Which means if you have added an element into Set and trying to insert duplicate element again, it will not be allowed. If add() returns false it means that element is not allowed in the Set and that is your duplicate.

======================================================

Solution 3 : with Time Complexity = O(2n)

Third solution takes advantage of another useful data structure, hash map. All you need to do is loop through the array using enhanced for loop and insert each element and its count into hash table.

In order to build map, you check if hash table contains the elements or not, if it is then increment the count otherwise insert element with count 1. Once you have this map ready, you can iterate over hashmap and print all those keys which has values greater than one. These are your duplicate elements. This is in fact a very good solution because you can extend it to found count of duplicates as well.

======================================================
Subscribe to this channel, and press bell icon to get some interesting videos on Selenium and Automation:

Follow me on my Facebook Page:

Let's join our Automation community for some amazing knowledge sharing and group discussion:

-~-~~-~~~-~~-~-
========================================================
Please watch: "Selenium & Automation Interview Preparation - By Naveen AutomationLabs"
-~-~~-~~~-~~-~- Subscribe to this channel, and press bell icon to get some interesting videos on Selenium and Automation:

Follow me on my Facebook Page:

Let's join our Automation community for some amazing knowledge sharing and group discussion on Telegram:

Paid courses (Recorded) videos:
📗 Get My Paid Courses at
Paid courses (Recorded) videos:
-------------------------------

✔️SOCIAL NETWORKS
--------------------------------

Support My Channel✔️Or Buy Me A Coffee
--------------------------------
✔️Thanks for watching!
देखने के लिए धन्यवाद
Благодаря за гледането
感谢您观看
Merci d'avoir regardé
Grazie per la visione
Gracias por ver
شكرا للمشاهدة ➡️Get Our Courses✔️
📗 Get My Paid Courses at
Paid courses (Recorded) videos:
-------------------------------

✔️SOCIAL NETWORKS
--------------------------------

Support My Channel✔️Or Buy Me A Coffee
--------------------------------
✔️Thanks for watching!
देखने के लिए धन्यवाद
Благодаря за гледането
感谢您观看
Merci d'avoir regardé
Grazie per la visione
Gracias por ver
شكرا للمشاهدة
Рекомендации по теме
Комментарии
Автор

King of the explanation, very clear and up to point. God Bless you!

selectiveeagle
Автор

Your videos are really awesome, never saw anyone explaining things at this level. Please carry on for other concepts too.

Baigan
Автор

Hi Naveen, Thanks for the amazing videos. I am preparing for Selenium with Java interview and referring your videos and I must say the way you explain, the concepts becomes very easy to understand for a JAVA naive like me as well.
One request, please increase the font size as its difficult to read your code in such small font.

chayakakati
Автор

String names[]={"Ankur", "Hero", "Arun", "Ankur", "Hero"};
HashMap<String, Integer> map = new HashMap<>();
for (String ch : names) {
if (map.containsKey(ch)) {
int val = map.get(ch);
map.put(ch, val + 1);
} else {
map.put(ch, 1);
}
}
System.out.println(map);
}
}

ankurbansal
Автор

I had this question in 3 consecutive interviews recently. But the only difference is they asked me to find duplicate and non-duplicate characters from a given string such as "ascedcsf". Your video is really very well organized and well explained.

tawbinable
Автор

awesome tutorial sir, thanks a lot for sharing, keep it up 👍👍🙂🙂

SmartProgramming
Автор

Hi Naveen, your explanation of the concepts are too good. I have learnt so many things while going thru your videos. One suggestion I would like to let you know that please increase font so it will be more visible when we watch your trainings in mobile as well.

Thanks,
Bharath.

bharathmatta
Автор

you are the best; i appreciate the work and time,

CrystalisDota
Автор

Thanks Naveen, have been struggling a lot to get this understanding, thanks a ton! 😊😊

antarabanerjee
Автор

Hey Naveen, Another option is to use keySet() to get the getValue()

selvakumarthevar
Автор

The third solution can be optimized
If(hashmap.get(name) == null){
Hashmap.put(name, counter)
}
else {
Print duplicate element(name)
}

In this case we need not go for entryset

ayazattar
Автор

one of the best solutions i have seen, it was so easy to understand the concepts. Thanks Naveen Sir:)

safarnama
Автор

Very well explain naveen thank you. I understand each & every part because of this video. I need optimize solution for few assignment like longest substring of non repeating character, intersecting of rectangles, no repeating first character in array, expression validation in java. If you give any idea it would help me lot .

rohitsable
Автор

Thanks Naveen. I understand each and every part because of this video.

gangadharmishra
Автор

There is one more question where we need to give the number of times a specific element is present i.e. for below array
String nameArray[] = {"Java", "C#", "Ruby", "Python", "Java", "C++", "C#", "AngularJS", "Java"};
it should return 3 for Java and 2 for C#.

For this we just need to add one extra line in HaspMap code:

System.out.println("The occurence of element "+entry.getKey()+" is "+ entry.getValue());

Full code below:

String nameArray[] = {"Java", "C#", "Ruby", "Python", "Java", "C++", "C#", "AngularJS", "Java"};
Map<String, Integer> map = new HashMap<String, Integer>();
for(String name: nameArray)
{
Integer count = map.get(name); // it will return null as no values are present for the key
if(count==null)
{
map.put(name, 1); //when its null add the value
}
else
{
map.put(name, ++count); // when it finds second occurrence of Java (i.e count =1 )we increase the count
}
}
System.out.println(map);

for(Map.Entry<String, Integer> entry:map.entrySet())
{
if(entry.getValue()>1)
{
System.out.println("The duplicate element is: "+entry.getKey());
System.out.println("The occurence of element "+entry.getKey()+" is "+ entry.getValue());
}

}

kshitijshrivastava
Автор

One of the best explanation I found.Thanks a lot, for sharing.

reetu
Автор

If i have 5 billions elements in java array along with duplicates then also is this the best solution.Because i have been asked this question in interview but i couldn't give them answer.

kalidindiprashanth
Автор

Thank you so much Naveen.. Really helpful..

priyangasubbiah
Автор

Thanks Naveen. That was crystal clear!

oopsididitagain
Автор

Hi Naveen, If we have n same element, it will print n-1 times the same element for the set solution you provided.For example {harsh, raj, harsh, kumar, harsh} . output will be harsh, harsh

Tondumal
welcome to shbcf.ru