Sort an array according to the elements of another array
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
This problem is often called relative sorting. You have one array, arr1, that you want to reorder, and another array, arr2, that defines the preferred order for some values. Elements that appear in arr2 should come first in that exact order, and values not mentioned in arr2 should usually be placed afterward in normal sorted order.
The Core Idea
The simplest solution is to build a priority map from arr2.
For example, if:
- '
arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]' - '
arr2 = [2, 1, 8, 3]'
then the priority map is:
- '
2 -> 0' - '
1 -> 1' - '
8 -> 2' - '
3 -> 3'
Any value found in that map should be sorted by its mapped priority. Any value not found should be placed later and sorted naturally.
Python Implementation
Output:
The tuple sort key does all the work:
- values from
arr2get group0and a priority index - values not in
arr2get group1and are ordered by their own value
Why This Works
The sort key imposes two layers of ordering:
- whether the element appears in
arr2 - what its rank or natural value is inside that group
That makes the rule explicit and easy to extend.
An Alternative Counting Approach
If the values are simple and duplicates matter heavily, another good solution is counting frequencies.
This approach is especially nice when you want full control over duplicate handling.
Time Complexity
The custom-sort solution typically runs in O(n log n) because it still relies on sorting arr1.
The counting version can be attractive when the number of distinct values is small relative to the total array size, but the right choice depends on the data and language.
In interviews, the custom-sort answer is usually enough because it is easy to explain and easy to verify. In production code, choose the version that your team will read correctly six months later. For most languages, clarity matters more than shaving a small constant factor from a relative-sort utility.
Common Pitfalls
A common mistake is forgetting to decide what happens to values in arr1 that are not present in arr2. Most versions of the problem want them sorted normally at the end.
Another mistake is using an order map but not handling duplicates carefully. The priority map tells you where a value belongs, but duplicates still need to be preserved in the result.
A third issue is assuming arr2 contains every possible value. Many real inputs do not, so the fallback ordering matters.
Summary
- Build a priority map from the reference array
arr2 - Sort
arr1so referenced values come first inarr2order - Place values not in
arr2afterward using normal ordering - A tuple sort key is a clean Python solution
- Counting frequencies is another good option when duplicates are important

