Given two arrays arr1 and arr2, where arr2 contains distinct elements and each element in arr2 is also in arr1, sort arr1 such that the relative order of items matches that in arr2. Elements not appearing in arr2 should be sorted in ascending order at the end.
Create a hash map from arr2 value to its index position. Sort arr1 with a custom comparator: if both elements are in arr2, compare by their index in arr2. If only one is in arr2, it comes first. If neither is in arr2, sort by value ascending.
This is a stable sorting problem where a reference array determines the order of a subset. The remaining elements follow standard ascending order.
Edge cases include arr2 having all elements (result matches arr2 order), arr2 having no elements (result is arr1 sorted ascending), and empty arrays.
The relative sort problem demonstrates custom ordering based on a reference array. Elements in the reference get ordered by position, while remaining elements follow natural ascending order. The comparator must handle three cases: both in reference, one in reference, or neither.
The custom comparator handles three cases: both elements in the reference array (compare by position), one element in reference (that element comes first), or neither in reference (compare by natural value). This three-case pattern appears in many sorting problems with partial ordering from an external reference.Example Input & Output
arr2 order: 22,28,8,6. Remaining: 17,44.
arr2 order: 1 then 2.
No arr2, sort ascending.
Empty.
arr2 order: 2,1,4,3,9,6. Remaining 7,19 sorted.
Algorithm Flow

Solution Approach
Build position map from arr2. Sort arr1: if both in map, compare positions; else sort by value.
Time O(n log n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] arr1, int[] arr2) {
Map<Integer,Integer> p=new HashMap<>();
for (int i=0;i<arr2.length;i++) p.put(arr2[i],i);
return Arrays.stream(arr1).boxed().sorted((a,b)->{
boolean ap=p.containsKey(a),bp=p.containsKey(b);
if (ap&&bp) return p.get(a)-p.get(b);
if (ap) return -1;
if (bp) return 1;
return a-b;
}).mapToInt(i->i).toArray();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
