Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Sorting
Relative Sort Array

Sort one array so that elements appearing in a reference array come first, in reference order, and the rest appear afterward in increasing order.

Acceptance 0%
Problem Statement

Problem

Given two integer arrays arr1 and arr2, reorder arr1 so that:

  1. The relative order of elements that appear in arr2 follows the order of arr2.
  2. Any elements from arr1 that do not appear in arr2 are placed at the end.
  3. 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 reorder
  • arr2: an integer array containing distinct values that define the preferred order

Output Format

  • Return a new array containing the elements of arr1 arranged according to the rules above.

Constraints

  • 1 <= arr1.length <= 1000
  • 1 <= arr2.length <= 1000
  • 0 <= arr1[i], arr2[i] <= 1000
  • All values in arr2 are distinct
  • Every value in arr2 appears in arr1
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.