Relative Sort Array in Python


Suppose we have two arrays arr1 and arr2, the elements of arr2 are unique, and all elements in arr2 are also present in arr1. We have to sort the elements of arr1 in such a way that the relative ordering of items in arr1 are the same as in arr2. If there are some elements that are not present in arr2, they should be placed at the end of arr1 in ascending order. So if the arr1 is like [2,3,1,3,2,4,6,7,9,2,19], and arr2 is like [2,1,4,3,9,6], then result will be [2,2,2,1,4,3,3,9,6,7,19]

To solve this, we will follow these steps −

  • create one map called D, and store the frequency of elements present in arr1
  • define two arrays res and temp
  • for each element i in arr2 −
    • for j in range 0 to D[i] – 1
      • append i into the res
    • D[i] := 0
  • for (key, value) pair in D
    • if value is not 0, then
      • for i := 0 to value – 1
        • add key into temp
  • sort temp array, add temp at the end of res, and return res

Example

Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def relativeSortArray(self, arr1, arr2):
      d = {}
      for i in arr1:
         if i not in d:
            d[i]= 1
         else:
            d[i]+=1
      res = []
      temp = []
      for i in arr2:
         for j in range(d[i]):
            res.append(i)
         d[i] =0
      for k,v in d.items():
         if v:
            for i in range(v):
               temp.append(k)
      temp.sort()
      res.extend(temp)
      return res
ob1 = Solution()
print(ob1.relativeSortArray([2,3,1,4,2,4,6,7,9,2,19] ,[2,1,4,3,9,6]))

Input

[2,3,1,3,2,4,6,7,9,2,19]
[2,1,4,3,9,6]

Output

[2, 2, 2, 1, 4, 4, 3, 9, 6, 7, 19]


Updated on: 18-May-2020

481 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements