Sort an array according to the other | Practice | GeeksforGeeks

Given two integer arrays A1[ ] and A2[ ] of size N and M respectively. Sort the first array A1[ ] such that all the relative positions of the elements in the first array are the same as the elements in the second array A2[ ].
See example for better understanding.
Note: If elements are repeated in the second array, consider their first occurance only.
Example 1:
Input:
N = 11 
M = 4
A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
A2[] = {2, 1, 8, 3}
Output: 
2 2 1 1 8 8 3 5 6 7 9
Explanation: Array elements of A1[] are
sorted according to A2[]. So 2 comes first
then 1 comes, then comes 8, then finally 3
comes, now we append remaining elements in
sorted order.

Example 2:
Input:
N = 11 
M = 4
A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
A2[] = {99, 22, 444, 56}
Output: 
1 1 2 2 3 5 6 7 8 8 9
Explanation: No A1[] elements are in A2[]
so we cannot sort A1[] according to A2[].
Hence we sort the elements in non-decreasing 
order.
Your Task:
You don't need to read input or print anything. Your task is to complete the function sortA1ByA2() which takes the array A1[ ], array A2[ ] and their respective size N and M as input parameters and returns the sorted array A1[ ] such that the relative positions of the elements in A1[ ] are same as the elements in A2[ ]. For the elements not present in A2[ ] but in A1[ ], it appends them at the last in increasing order. 
Expected Time Complexity: O(N * Log(N)).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ N, M ≤ 106
1 ≤ A1[i], A2[i] ≤ 106 
0
pratikbhankhodiya1 day ago
vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M) 
    {
        map<int,int> mp;
        int i=0;
        for(auto it:A1) mp[it]++;
        for(auto it:A2){
            while(mp[it]-->0) A1[i++]=it;
        }
        for(auto &pair:mp){
            auto it=pair.first;
            auto freq=pair.second;
            while(freq-->0) A1[i++]=it;
        }
        return A1;
    } 
0
aakarshgoel102 days ago
 
       public static int[] sortA1ByA2(int A1[], int N, int A2[], int M) {       ArrayList<Integer> result = new ArrayList<>();       HashMap<Integer, Integer> hashmap = new HashMap<>();       for (int ip = 0; ip < N; ip++) {           if (hashmap.containsKey(A1[ip])) {               hashmap.put(A1[ip], hashmap.get(A1[ip]) + 1);           } else {               hashmap.put(A1[ip], 1);           }
       }
       for (int i = 0; i < M; i++) {           if (hashmap.containsKey(A2[i])) {               for (int j = 0; j < hashmap.get(A2[i]); j++) {                   result.add(A2[i]);               }               hashmap.remove(A2[i]);           }       }       ArrayList<Integer> remainingArray = new ArrayList<>();       int k = 0;       for (Map.Entry<Integer, Integer> map : hashmap.entrySet()) {           for (int j = 0; j < map.getValue(); j++) {               remainingArray.add(map.getKey());           }       }       Collections.sort(remainingArray);       for (int elem : remainingArray) {           result.add(elem);       }       int finalArray[] = new int[result.size()];       for (int i = 0; i < finalArray.length; i++) {           finalArray[i] = result.get(i);       }
       return finalArray;
   }
}
 
// { Driver Code Starts.class Main {public static void main (String[] args) { Scanner sc=new Scanner(System.in);  int t=sc.nextInt();  while(t-->0) {     int n=sc.nextInt();     int m=sc.nextInt();     int a1[]=new int[n];     int a2[]=new int[m];          for(int i=0;i<n;i++)     a1[i]=sc.nextInt();          for(int i=0;i<m;i++)     a2[i]=sc.nextInt();     Solution ob=new Solution();     a1 = ob.sortA1ByA2(a1,n,a2,m);     for(int x:a1)     System.out.print(x+" ");          System.out.println(); }} 
}
 // } Driver Code Ends
0
gulrezalam1 week ago
what is meaning of        
 
         Collections.sort(a,(n1,n2)->{   return n1-n2;  });
 
 
 
where a is an array
0
akshayjadhav32 weeks ago
vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M)    {              multiset<int>s{A1.begin(),A1.begin()+N};       vector<int>v;       int i=0;       while(i<M)       {                                            while(s.find(A2[i])!=s.end())           {               auto it=s.find(A2[i]);               v.push_back(*it);               s.erase(it);                                                        }                                 i++;                  }                      auto it1=s.begin();           while(it1!=s.end())           {               v.push_back(*it1);               it1++;           }                                                return v;          }
0
arya049442 weeks ago
 vector<int> sortA1ByA2(vector<int> A1, int N, vector<int> A2, int M) 
    {
        //Your code here
        map<int,int> mp;
        for(auto a:A1){
            mp[a]++;
        }
        int i=0;
        for(auto a:A2){
            int k=mp[a];
            mp[a]=0;
            while(k--){
                A1[i++]=a;
            }
            
        }
        
        for(auto m:mp){
            int k=m.second;
            m.second=0;
            while(k--){
                A1[i++]=m.first;
            }
        }
        
        return A1;
    } 
+1
sriniprasanna773 weeks ago
This can be done using hashmap by keeping track of any elements and their occurrences in a1[].
Sort a1[] and (a) clone into temp[]; (b) create an HashMap with key = a[i], value = occurenceCountloop through a2[] and find value from HashMap for a2[i]if mapvalue > 0, then a2[] has element that occurs in a1[]start assiging a[i] with the element for mapvalue number of times (occurences)Most important step : set -1 as value for all matching elements in hashmapFinally, copy the remainder elements from temp over to a1[] continuing the index
Sort a1[] and (a) clone into temp[]; (b) create an HashMap with key = a[i], value = occurenceCount
loop through a2[] and find value from HashMap for a2[i]
if mapvalue > 0, then a2[] has element that occurs in a1[]
start assiging a[i] with the element for mapvalue number of times (occurences)
Most important step : set -1 as value for all matching elements in hashmap
Finally, copy the remainder elements from temp over to a1[] continuing the index
public static int[] sortA1ByA2(int a1[], int N, int a2[], int M)   {       //Your code here int[] temp = new int[a1.length];  HashMap<Integer,Integer> a1Map = new HashMap<>();  Arrays.sort(a1);  for(int i = 0; i < N; i++) {  a1Map.put(a1[i],a1Map.getOrDefault(a1[i], 0) != 0?a1Map.get(a1[i])+1:1);  temp[i] = a1[i]; }    int idx = 0; for (int n: a2) {  int mapVal = a1Map.getOrDefault(n,0);    if (mapVal > 0) {   for(int i=0; i<mapVal; i++) {    a1[idx] = n;    idx++;   }   a1Map.put(n,-1); //important line  } }    for (int n: temp) {  int mapVal = a1Map.get(n);    if (mapVal > 0) {   a1[idx] = n;   idx++;  } }  return a1;   }
0
harshilgupta00993 weeks ago
vector<int> sortA1ByA2(vector<int> arr1, int n, vector<int> arr2, int m) 
    {
        //Your code here
        vector<int> ans;
        unordered_map<int,int> umap;
        for(int i=0;i<n;i++){
            umap[arr1[i]]++;
        }
        for(int i=0;i<m;i++){
            while(umap[arr2[i]]!=0){
                ans.push_back(arr2[i]);
                umap[arr2[i]]--;
            }
            if(umap[arr2[i]]==0)
                umap.erase(arr2[i]);
        }
        vector<int> v;
        for(auto x:umap){
            while(x.second!=0){
                v.push_back(x.first);
                x.second--;
            }
            
        }
        sort(v.begin(),v.end());
        for(int x:v)
            ans.push_back(x);
        return ans;
    } 
0
shubham211019973 weeks ago
public static int[] sortA1ByA2(int arr1[], int n, int arr2[], int m)
   {
      /* Naive Solution
      ArrayList<Integer>a=new ArrayList<Integer>();
 for(int i=0;i<n;i++)
  a.add(arr1[i]);
 ArrayList<Integer>b=new ArrayList<Integer>();
 for(int i=0;i<m;i++) {
  b.add(arr2[i]);
 }
 int arr[]=new int[n];
 int k=0;
 for(int i=0;i<m;i++) {
  while(a.contains(b.get(i))) {
        arr[k++]=b.get(i);
   a.remove(b.get(i));
  }
 }
 Collections.sort(a,(n1,n2)->{
  return n1-n2;
 });
 for(int i=0;i<a.size();i++) {
     arr[k++]=a.get(i);
 }
 
 return arr;*/
 int arr[]=new int[n];
 int k=0;
 TreeMap<Integer,Integer> h=new TreeMap<>();
 for(int i:arr1){
     h.put(i,h.getOrDefault(i,0)+1);
 }
 for(int i:arr2){
    if(h.containsKey(i)==true){
        while(h.get(i)!=0){
            arr[k++]=i;
            h.put(i,h.get(i)-1);
        }
        h.remove(i);
    }
 }
//   Collections.sort(h,(a,b)->{
//      return a-b;  
//   });
  for(Entry<Integer,Integer> e : h.entrySet()){
      for(int p=0;p<e.getValue();p++)
          arr[k++]=e.getKey();
      }
  
       
  return arr;    
   }
0
shubham211019973 weeks ago
public static int[] sortA1ByA2(int arr1[], int n, int arr2[], int m)
   {
      ArrayList<Integer>a=new ArrayList<Integer>();
 for(int i=0;i<n;i++)
  a.add(arr1[i]);
 ArrayList<Integer>b=new ArrayList<Integer>();
 for(int i=0;i<m;i++) {
  b.add(arr2[i]);
 }
 int arr[]=new int[n];
 int k=0;
 for(int i=0;i<m;i++) {
  while(a.contains(b.get(i))) {
        arr[k++]=b.get(i);
   a.remove(b.get(i));
  }
 }
 Collections.sort(a,(n1,n2)->{
  return n1-n2;
 });
 for(int i=0;i<a.size();i++) {
     arr[k++]=a.get(i);
 }
 
 return arr;
   }
0
ravinuthalavamsikrishna3 weeks ago
    def relativeSort (self,A1, N, A2, M):       # Your Code Here       d={}       for i in A1:           d[i]=d.get(i,0)+1       l=[]       l2=[]       for i in A2:           if i in d.keys():               l+=[i]*(d[i])               del d[i]       l2=[]       for i,j in d.items():           l2+=[i]*j       l2.sort()       l+=l2       return l
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.