Relative Sort Array

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Relative Sort Array

Approach

Build a map from arr2 values to their indices (defining custom order). Sort arr1 with a comparator: if both elements are in arr2, sort by their arr2 index. If only one is in arr2, it comes first. If neither is in arr2, sort numerically.

Complexity Analysis

Time
O(n log n)
Space
O(n)

Pattern

Custom Order Sort

Why It Works

The order map encodes arr2 as a priority system. The three-branch comparator handles all cases: both in arr2 (use their relative order), one in arr2 (prioritize it), neither in arr2 (default ascending). This produces the exact custom ordering requested.

Updated Feb 2026