Lists in HashMap in JAVA example ,ZOHO Technical Round Question,Maps usage in java - UCS - Unleash-Coding-Skills

Wednesday, 9 May 2018

Lists in HashMap in JAVA example ,ZOHO Technical Round Question,Maps usage in java - UCS

Question:

Program for Finding all the duplicate entries in an array and print the indexes using JAVA. This is also a question asked in ZOHO software developer interview.

I have written the solution for this question using JAVA collections.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
 public static void main(String[] args) {
     Scanner s = new Scanner(System.in);
     List <Integer> l = new ArrayList<>();
     HashMap<Integer,ArrayList<Integer> > hm = new HashMap<>();
     int n,r;
     n=s.nextInt();
     for(int i=0;i<n;i++)
     {
        r = s.nextInt();
        l.add(r);
     }
    for(int i=0;i<n;i++)
    {
        ArrayList<Integer>l1 = new ArrayList<>();
        l1.add(i);
        int p= l.get(i);
        if(hm.get(p)==null)
        hm.put(p,l1);
        else
        {
          l1 = hm.get(p);
            l1.add(i);
            hm.put(p,l1);
        }
    }
Iterator<Map.Entry<Integer,ArrayList<Integer> > >itr = hm.entrySet().iterator();
     while(itr.hasNext())
     {
          HashMap.Entry<Integer,ArrayList<Integer> >mp = itr.next();
        int k = mp.getKey();
         ArrayList <Integer> l3 = mp.getValue();
         System.out.printf("%d :",k);
         if(l3.size()>1)
         {
        for(int p=1;p<l3.size();p++)
        {
            System.out.printf("%d ",l3.get(p));
        }
         }
         else
         {
             System.out.printf("no duplicates");
         }
         System.out.printf("\n");
     }
   }
}
>
Input (stdin)
6
1
2
2
2
4
4
Your Output (stdout)
1 :no duplicates
2 :2 3 
4 :5 

Pairs in  TreeSet tutorial  along with overriding sorting for our  usage:


Happy Coding...................


Happy Coding............


No comments:

Post a comment