Relative Sort Array

Medium~15 min

Given two arrays arr1 and arr2, sort the elements of arr1 such that:

  1. Elements that appear in arr2 come first, ordered according to their position in arr2
  2. Elements that do not appear in arr2 are placed at the end, sorted in ascending order

Each element in arr2 is distinct. Every element in arr2 is also present in arr1.

Return the sorted array.

Examples

Example 1
Input: arr1 = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], arr2 = [2, 1, 4, 3, 9, 6]
Output: [2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19]
Explanation: Elements from arr2 come first in arr2's order (with duplicates): 2,2,2,1,4,3,3,9,6. Remaining elements [7,19] are appended in ascending order.
Example 2
Input: arr1 = [28, 6, 22, 8, 44, 17], arr2 = [22, 28, 8, 6]
Output: [22, 28, 8, 6, 17, 44]
Explanation: Elements from arr2 in order: 22, 28, 8, 6. Remaining [17, 44] sorted ascending.
Example 3
Input: arr1 = [1, 2, 3], arr2 = [3, 2, 1]
Output: [3, 2, 1]
Explanation: All elements are in arr2. Sorted in arr2's order: 3, 2, 1.

Constraints

  • 1 <= arr1.length <= 1000
  • 0 <= arr1[i] <= 1000
  • 1 <= arr2.length <= arr1.length
  • All elements of arr2 are distinct
  • Each element of arr2 is present in arr1
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run