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

แชร์
ฝัง
  • เผยแพร่เมื่อ 22 พ.ย. 2017
  • 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:
    th-cam.com/users/Naveen%20Au...
    Follow me on my Facebook Page:
    / naveenqtpexpert
    Let's join our Automation community for some amazing knowledge sharing and group discussion:
    t.me/joinchat/COJqZQ4enmEt4JA...
    ~-~~-~~~-~~-~
    Follow my Site/Blog: www.naveenautomationlabs.com
    ========================================================
    Please watch: "Selenium & Automation Interview Preparation - By Naveen AutomationLabs"
    • Selenium & Automation ...
    ~-~~-~~~-~~-~ Subscribe to this channel, and press bell icon to get some interesting videos on Selenium and Automation:
    th-cam.com/users/Naveen%20Au...
    Follow me on my Facebook Page:
    / naveenqtpexpert
    Let's join our Automation community for some amazing knowledge sharing and group discussion on Telegram:
    t.me/joinchat/COJqZUPB02r5sB7...
    Paid courses (Recorded) videos:
    Java & Selenium Course: www.naveenautomationlabs.com/p...
    API Course: www.naveenautomationlabs.com/p... ➡️Get Our Courses✔️
    📗 Get My Paid Courses at
    Paid courses (Recorded) videos:
    Java & Selenium Course: www.naveenautomationlabs.com/p...
    API Course: www.naveenautomationlabs.com/p...
    -------------------------------
    ✔️SOCIAL NETWORKS
    Facebook: / naveenqtpexpert
    Twitter: / naveenkhunteta
    Blog: www.naveenautomationlabs.com
    --------------------------------
    Support My Channel✔️Or Buy Me A Coffee
    Paypal: paypal.me/naveenkhunteta
    Google Pay: naveenanimation20@gmail.com
    --------------------------------
    ✔️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:
    Java & Selenium Course: www.naveenautomationlabs.com/p...
    API Course: www.naveenautomationlabs.com/p...
    -------------------------------
    ✔️SOCIAL NETWORKS
    Facebook: / naveenqtpexpert
    Twitter: / naveenkhunteta
    Blog: www.naveenautomationlabs.com
    --------------------------------
    Support My Channel✔️Or Buy Me A Coffee
    Paypal: paypal.me/naveenkhunteta
    Google Pay: naveenanimation20@gmail.com
    --------------------------------
    ✔️Thanks for watching!
    देखने के लिए धन्यवाद
    Благодаря за гледането
    感谢您观看
    Merci d'avoir regardé
    Grazie per la visione
    Gracias por ver
    شكرا للمشاهدة
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 90

  • @selectiveeagle4040
    @selectiveeagle4040 4 ปีที่แล้ว +5

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

  • @mudaseer21
    @mudaseer21 5 ปีที่แล้ว +1

    Your teaching is apple of my eye

  • @Tidda420
    @Tidda420 3 ปีที่แล้ว +3

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

  • @tawbinable
    @tawbinable 4 ปีที่แล้ว

    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.

  • @chayakakati1110
    @chayakakati1110 5 ปีที่แล้ว +4

    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. Thanks.....

  • @kshitijshrivastava9881
    @kshitijshrivastava9881 6 ปีที่แล้ว +2

    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 map = new HashMap();
    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 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());
    }

    }

  • @ankurbansal904
    @ankurbansal904 5 ปีที่แล้ว +17

    String names[]={"Ankur","Hero","Arun","Ankur","Hero"};
    HashMap 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);
    }
    }

    • @nazimkhan9080
      @nazimkhan9080 2 ปีที่แล้ว

      String names[]= {"Java","javaScript","Ruby","C","Python","Java","C"};
      Map storeMap=new HashMap();
      for(String name:names){
      Integer count= storeMap.put(name, 1);
      if(count!=null){
      System.out.println("Duplicate element is:::"+name);}}

  • @gangadharmishra2138
    @gangadharmishra2138 6 ปีที่แล้ว

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

  • @SmartProgramming
    @SmartProgramming 5 ปีที่แล้ว +2

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

  • @oopsididitagain8572
    @oopsididitagain8572 5 ปีที่แล้ว +1

    Thanks Naveen. That was crystal clear!

  • @programmingvideo1744
    @programmingvideo1744 5 ปีที่แล้ว +1

    Amazing broad concepts !

  • @safarnama6608
    @safarnama6608 5 ปีที่แล้ว

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

  • @priyangasubbiah8317
    @priyangasubbiah8317 4 ปีที่แล้ว +1

    Thank you so much Naveen.. Really helpful..

  • @antarabanerjee7314
    @antarabanerjee7314 3 ปีที่แล้ว

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

  • @bharathmatta3857
    @bharathmatta3857 5 ปีที่แล้ว +2

    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.

  • @meditationandrelaxationmus741
    @meditationandrelaxationmus741 5 ปีที่แล้ว +1

    Nice video concept is so clear

  • @CrystalisDota
    @CrystalisDota 2 ปีที่แล้ว +1

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

  • @selvakumarthevar518
    @selvakumarthevar518 6 ปีที่แล้ว +2

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

  • @anuradharamisetty
    @anuradharamisetty 5 ปีที่แล้ว

    Really good teaching

  • @sanjuk2484
    @sanjuk2484 5 ปีที่แล้ว

    Your genius naveen

  • @ghulamanosh5564
    @ghulamanosh5564 3 ปีที่แล้ว

    Thank you Naveen.

  • @reetu1326
    @reetu1326 4 ปีที่แล้ว

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

    • @vanajabethina5991
      @vanajabethina5991 4 ปีที่แล้ว

      w.a p to find the words number of time repeating using hashmap (string="web internet web chrome internet safari") how can i solve please tell me frds or any video links share me frds last intreviewer
      ask me

  • @rohitsable9341
    @rohitsable9341 6 ปีที่แล้ว +2

    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 .

  • @saisrikar7987
    @saisrikar7987 6 ปีที่แล้ว

    excellent video sir.Please make more videos regd Java

  • @ayazattar1641
    @ayazattar1641 6 ปีที่แล้ว +5

    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

    • @averageconsumer5374
      @averageconsumer5374 4 ปีที่แล้ว

      not optimised. if you are going to print like that, duplicate elements will printed many times

  • @sanjayadahal1743
    @sanjayadahal1743 4 ปีที่แล้ว

    Hi Navee,n for HashMap in the else statement if i print the item or simple return that item do i really need to iterate over hashMap to find the count having value greater than 1.

  • @shubhamprajapati7150
    @shubhamprajapati7150 2 ปีที่แล้ว

    Aap kaafi achha padha rahe ho sir

  • @santhoshthaduri899
    @santhoshthaduri899 6 ปีที่แล้ว +1

    Thanks naveen, also could you please make same thing using recursive function. It will help us.

  • @ujjwalverma7787
    @ujjwalverma7787 5 ปีที่แล้ว +1

    sir, please help me i really confuse between them what is the difference between the "array.length and array.length()" some time array.length will work and some time array.length() will work. is there is any rules for is for using it? with String arr.length() will work but when we use an integer type, its work with array.length.

  • @kalidindiprashanth7363
    @kalidindiprashanth7363 5 ปีที่แล้ว +6

    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.

  • @ranjanentertainment5602
    @ranjanentertainment5602 6 ปีที่แล้ว +2

    Hey Naveen,
    thanks for uploading such type of program but i have one inside (store.addname==false)
    Set s=new HashSet();
    for (String name : names) {
    if(store.add(name)==false){

  • @mandeep3445
    @mandeep3445 4 ปีที่แล้ว

    Thank you.

  • @piyumigunawardana4610
    @piyumigunawardana4610 4 ปีที่แล้ว

    thank you!!

  • @ssandeep79
    @ssandeep79 6 ปีที่แล้ว

    What if we sort the array and then compare only contiguous cells /indeces? That might be quicker.

  • @cookhjj
    @cookhjj 4 ปีที่แล้ว

    We can iterate hash map like this
    for(Map.Entry entrySet : map.entrySet())
    {
    if((int)entrySet.getValue()>1)
    System.out.println("Duplicate element in an array:"+ (String)entrySet.getKey());
    }

  • @suhaschavan8406
    @suhaschavan8406 4 ปีที่แล้ว

    Navin, need help can you suggest solution for finding int duplicate from scanner

  • @uk7023
    @uk7023 5 ปีที่แล้ว +1

    Naveen Thanks for sharing video but your logic using Hashset will not work if we will have more than two elements having same vaues in an array. Can You check that case?

  • @jarvisfriday7452
    @jarvisfriday7452 3 ปีที่แล้ว

    Hi Naveen, Can we use Treeset instead of hashset?

  • @gadinaresh5458
    @gadinaresh5458 4 ปีที่แล้ว

    In those concepts which is efficient way to use.....so plzz reply

  • @fred2647
    @fred2647 2 ปีที่แล้ว

    Hey everyone, can anyone help me to find answer to this question? When we make use of in-built Java instructions in the video to check if the element is already in a Set, or HashMap, .... (e.g. , if (map.containsKey(ch))......) does Java do an additional iteration internally (abstract to the programmer) to check the whole set or hash map for the duplicates and therefore adding to the time complexity of the whole code?

  • @maksymosipa9287
    @maksymosipa9287 5 ปีที่แล้ว +3

    100% they will ask you, in each video on selenium and java you are telling this ))

    • @dfeefwfg141
      @dfeefwfg141 5 ปีที่แล้ว

      yea because whatever he is teaching everything asked in interview atleast i got several interview questions from his videos

  • @Tondumal16622
    @Tondumal16622 ปีที่แล้ว

    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

  • @fathimasyed4232
    @fathimasyed4232 3 ปีที่แล้ว +1

    I like Hashset :)

  • @vinodaraaj
    @vinodaraaj ปีที่แล้ว

    Using HashMap also we can make it simple. but when we need to get the total count of duplicate we can modify the value fi key exist .

  • @shoryabeohar1816
    @shoryabeohar1816 6 ปีที่แล้ว +8

    thanks amzing videao ..one request could you pls increase the fonts of eclipse..would be a great while watching

  • @Randoms147
    @Randoms147 4 ปีที่แล้ว

    which ide u used in this video?

  • @GulbargaRamNavamiUstav
    @GulbargaRamNavamiUstav 4 ปีที่แล้ว +2

    I seen many channels but not standard one like this

  • @ravirsoni
    @ravirsoni 6 ปีที่แล้ว

    Why here Object created with Parent Interface Reference ?
    We can also create the object as per below whats the problem here ?
    HashMap storeMap = new HashMap() instead of Map storeMap = new HashMap();
    HashSet store = new HashSet() instead of Set store = new HashSet();
    can someone explain this please ? Thanks in Advance.

  • @abheeshchandran1625
    @abheeshchandran1625 5 ปีที่แล้ว +1

    please add printing pyramid pattern in java interview question

  • @a_36_atharvathosar11
    @a_36_atharvathosar11 3 ปีที่แล้ว +1

    for String s = {"Java", "JavaScript", "Ruby", "Python", "Java", "C", "C", "Java"}, The first solution will not work. It will show "Java" Three times. Anyways, I would like to thank you for making these great tutorials.

  • @kirtihoney3822
    @kirtihoney3822 4 ปีที่แล้ว

    super explaination please zoom the code while you explaining for better view..sometimes its not clear view

    • @BikramTechie
      @BikramTechie 3 ปีที่แล้ว

      The code is clearly visible, you can change . you can change quality to 720p or 1080p

  • @user-ns8ht9tu3d
    @user-ns8ht9tu3d 4 หลายเดือนก่อน

    Hey Naveen u can do video for How to Find Duplicates Elements in Normal Int arrays?

  • @ayeshazakria2215
    @ayeshazakria2215 2 ปีที่แล้ว

    Do you have series of Data Structures ?

  • @AjayKumar-ye2cu
    @AjayKumar-ye2cu 5 ปีที่แล้ว

    Best solution is HashMap because 1st(Bruteforce) and 2nd(Set) can only compare 2 elements.But using HashMap we can find N no. of duplicate elements

    • @Nancy-xd7bp
      @Nancy-xd7bp 5 ปีที่แล้ว

      can you provide the solution with HashMap?

    • @priteshpatel4312
      @priteshpatel4312 4 ปีที่แล้ว +1

      @@Nancy-xd7bp here you go:String a1[]= {"java","php","python","java","c","c#","php","java"};
      HashMap map=new HashMap();
      for(String myNames : a1)
      {
      if(map.containsKey(myNames))
      {
      int count=map.get(myNames);
      map.put(myNames, count+1);
      }
      else
      {
      map.put(myNames, 1);
      }
      }
      System.out.println(map);

    • @kiranemmila
      @kiranemmila 4 ปีที่แล้ว

      @@priteshpatel4312 superb solution...thank you

  • @savitha1110
    @savitha1110 6 ปีที่แล้ว

    By using Hashset ---> This will print Java 2 times , if the there more than 2 occurrence of the same element . {"Java","Java","Java"}

  • @anilpal8333
    @anilpal8333 4 ปีที่แล้ว

    Hi how internally set remove duplicate in o(n) can you explain it
    Which add method call and how it will remove any object which is duplicate.

    • @sayanbhaumik5739
      @sayanbhaumik5739 4 ปีที่แล้ว

      Set by default stores only unique value in it. So here add(value) checks if the particular value is stored in it or not. If it finds the value then it will not add it in the set otherwise it will add. Let me know if i am clear.

    • @anilpal8333
      @anilpal8333 4 ปีที่แล้ว +1

      @@sayanbhaumik5739 how it will verify weather it object is present previously if bean object doesn't override hashcode and equals method

  • @bishalram481
    @bishalram481 6 ปีที่แล้ว

    Can you explain why the j value is not starting from 0 why it's started j=I+1;

    • @sachin21890
      @sachin21890 6 ปีที่แล้ว

      you would not want to compare any element with itself, otherwise all the elements will be printed as duplicate. Its j=i+1 because you want to compare with next element onward.

  • @naveenreddy127
    @naveenreddy127 4 ปีที่แล้ว +1

    String[] names = {"java","phython","java","c#","phython",".net"};
    Arrays.stream(names)
    .filter(name -> Collections.frequency(Arrays.asList(names), name) > 1)
    .collect(Collectors.toSet())
    .forEach(System.out::println);

  • @relax_habibi
    @relax_habibi 2 ปีที่แล้ว

    Hi naveen, i could not find a solution to check for duplicates in this array: integer array [12,12,7,7,7,7,7] , can you please help?

    • @sunithasharma4658
      @sunithasharma4658 8 หลายเดือนก่อน +1

      public static void main(String[] args) {
      int[] arr = {1, 5, 12, 12,7,7,7,7};
      Set uniqueSet = new HashSet();
      Set duplicates = new HashSet();
      for (int num : arr) {
      if (!uniqueSet.add(num)) {
      duplicates.add(num);
      }
      }
      if (!duplicates.isEmpty()) {
      System.out.println("Duplicate elements in the array without repetition:");
      for (int duplicate : duplicates) {
      System.out.println(duplicate);
      }
      } else {
      System.out.println("There are no duplicate elements in the array");
      }
      }

  • @srividyan7979
    @srividyan7979 6 ปีที่แล้ว +1

    Hi Naveen,
    thanks for sharing.iam getting output as shown below, how can i get only one value, can u solve please
    String names[]= {"java","phython","java","c#","phython",".net"};
    Map storemap=new HashMap();
    for(String name : names) {
    Integer count=storemap.get(name);
    if(count==null) {
    storemap.put(name, 1);
    }else {
    storemap.put(name,++count);
    }
    //get the value from this hashmap
    Set entryset= storemap.entrySet();
    for(Entry entry : entryset) {
    if (entry.getValue()>1) {
    System.out.println("Duplicate value is :"+entry.getKey());
    }
    }
    }
    output:
    Duplicate value is :java
    Duplicate value is :java
    Duplicate value is :java
    Duplicate value is :phython
    Duplicate value is :java
    Duplicate value is :phython

    • @varshab9967
      @varshab9967 6 ปีที่แล้ว

      Hi Srividya,
      End the first for loop before getting the value from HashMap.Hope this will help

    • @vishnuvardhanreddya2663
      @vishnuvardhanreddya2663 5 ปีที่แล้ว

      String names[]= {"java","phython","java","c#","phython",".net"};

      Map storemap=new HashMap();
      for(String name : names) {
      Integer count=storemap.get(name);
      if(count==null) {
      storemap.put(name, 1);
      }else {
      storemap.put(name,++count);
      }
      //get the value from this hashmap

      }
      Set entryset= storemap.entrySet();
      for(Entry entry : entryset) {
      if (entry.getValue()>1) {
      System.out.println(entry.getValue()+" times string "+entry.getKey()+"duplicated");
      }

      }

  • @MultiPrasad99
    @MultiPrasad99 4 ปีที่แล้ว +3

    Using HashMap also we can make it simple. I am checking for duplicate numbers so code is written with int. Like this...
    int a[]= {2,2,4,6,7,6,9,9};
    HashMap map = new HashMap();
    for(Integer num1:a) {
    if(map.put(num1, num1)!=null) {
    System.out.println("Duplicate using Hashmap is: "+ num1);
    }
    }

  • @ayeshazakria2215
    @ayeshazakria2215 2 ปีที่แล้ว

    pls use simple for loops

  • @AkilaHemal
    @AkilaHemal 4 ปีที่แล้ว +1

    in first example (int i=0 ; i

  • @kaustavdas3347
    @kaustavdas3347 ปีที่แล้ว

    I think there is the bug in this code I am not sure , but let assume String a[] = {"Java", "Python", "C", "C#", "C++", "Go", "C", "C", "Java", "Java"}; how this should with your code .

  • @sarathkumar4845
    @sarathkumar4845 2 ปีที่แล้ว

    How to find non duplicates in java please help me

  • @abhinashpatro2922
    @abhinashpatro2922 5 ปีที่แล้ว

    what is time complexity?

    • @fcgisarah
      @fcgisarah 5 ปีที่แล้ว

      The amount of time it takes for completion.

  • @apzalbahin
    @apzalbahin 3 ปีที่แล้ว

    String[] dupArray={"Mumbai","Chennai","Delhi","Kochi","Chennai","Kochi","Trivandrum","Delhi"};
    Map myMap=new HashMap();
    int counter=0;
    for (String city:dupArray) {
    if(myMap.put(city,++counter)!=null){
    System.out.println("Duplicate Value="+city);
    }
    }

  • @sheekhachauhan
    @sheekhachauhan 3 ปีที่แล้ว

    write a javascript code to perform the following on n array N containing the following{"welcome", "friends"} (i)Add "try" to array N.(ii)Join array N to another array M. (iii)Delete the last element from the array M. (iv)sort the array (v)Display the array in reverse. pls solve this.. if u're a real teacher

  • @nazimkhan9080
    @nazimkhan9080 2 ปีที่แล้ว

    String names[]= {"Java","javaScript","Ruby","C","Python","Java","C"};
    Map storeMap=new HashMap();
    for(String name:names){
    Integer count= storeMap.put(name, 1);
    if(count!=null){
    System.out.println("Duplicate element is:::"+name);}}