- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 j in range 0 to D[i] – 1
- for (key, value) pair in D
- if value is not 0, then
- for i := 0 to value – 1
- add key into temp
- for i := 0 to value – 1
- if value is not 0, then
- sort temp array, add temp at the end of res, and return res
Example
Let us see the following implementation to get better understanding −
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]
- Related Articles
- Sort Array By Parity in Python
- Absolute and Relative Imports in Python
- Make numbers in array relative to 0 – 100 in JavaScript
- Find array with k number of merge sort calls in Python
- Program to sort array by increasing frequency of elements in Python
- Constructing an array of addition/subtractions relative to first array element in JavaScript
- Sort Byte Array in Java
- Sort an Array in C++
- Sort Transformed Array in C++
- sort() in Python
- Finding relative order of elements in list in Python
- Program to sort an array based on the parity values in Python
- Python program to sort the elements of an array in ascending order
- Python program to sort the elements of an array in descending order
- Sort array based on another array in JavaScript

Advertisements