Facebook Pixel

Relative Sort Array

Problem Description

Given two arrays arr1 and arr2, sort arr1 so that the elements appear in the same relative order as they appear in arr2. Elements that don't appear in arr2 should be placed at the end in ascending order.

Input: Two arrays of integers

  • arr1: Array to be sorted
  • arr2: Array defining the ordering

Output: Array arr1 sorted according to the order in arr2

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: Elements from arr2 appear first in that order: 23), 11), 41), 32), 91), 61)
             Elements not in arr2 appear last in ascending order: 7, 19

Input: arr1 = [28, 6, 22, 8, 44, 17], arr2 = [22, 28, 8, 6]
Output: [22, 28, 8, 6, 17, 44]
Explanation: Elements in arr2 order: 22, 28, 8, 6
             Elements not in arr2: 17, 44 (sorted ascending)

Input: arr1 = [5, 5, 5, 5], arr2 = [5]
Output: [5, 5, 5, 5]
Explanation: All elements appear in arr2, so they maintain their order
Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro