Sort one array so that elements appearing in a reference array come first, in reference order, and the rest appear afterward in increasing order.
Problem
Given two integer arrays arr1 and arr2, reorder arr1 so that:
- The relative order of elements that appear in
arr2follows the order ofarr2. - Any elements from
arr1that do not appear inarr2are placed at the end. - Those remaining elements are sorted in ascending order.
Return the reordered array.
This is a custom sorting problem: the second array defines the priority order for a subset of values, while all other values are handled normally at the end.
Input Format
arr1: an integer array to reorderarr2: an integer array containing distinct values that define the preferred order
Output Format
- Return a new array containing the elements of
arr1arranged according to the rules above.
Constraints
1 <= arr1.length <= 10001 <= arr2.length <= 10000 <= arr1[i], arr2[i] <= 1000- All values in
arr2are distinct - Every value in
arr2appears inarr1
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
Place values in the order given by arr2, preserving multiplicity. Then append numbers not in arr2 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
The values in arr2 come first in that order. The remaining values 17 and 44 are appended sorted.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.