Skip to main content

Relative Sort Array

EasyArraySorting

Description

Sort arr1 such that relative ordering follows arr2, remaining elements sorted in ascending order at end. Return the result as an array.

Examples

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:

Ordered by arr2, then remaining sorted.

Input:arr1 = [1], arr2 = [1]
Output:[1]
Explanation:

Both arrays contain a single element 1. The sorted result is [1].

Input:arr1 = [5,8,3,5,1,8,2], arr2 = [8,5,2]
Output:[8,8,5,5,2,1,3]
Explanation:

First place all 8s (appears twice), then all 5s (appears twice), then all 2s (appears once) following arr2's order. Remaining elements 1 and 3 are sorted in ascending order at the end.

Constraints

  • 1 ≤ arr1.length, arr2.length ≤ 1000

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.