Design Gurus Logo
Relative Sort Array (easy)

Problem Statement

You are given two integers arrays arr1 and arr2. All elements of the arr2 are distinct, and present in arr1.

Sort the array arr1 such that relative orders of elements of arr1 should be the same as in arr2. If any elements in arr1 not found in arr2 should come at the end, sorted in ascending order.

Examples

Example 1:

  • Input: arr1 = [8, 1, 2, 3, 4, 8, 9], arr2 = [4, 3, 2, 1]
  • Expected Output: [4, 3, 2, 1, 8, 8, 9]
  • Justification: The elements in arr1 that are also in arr2 are arranged in the arr2 order first (4, 3, 2, 1), followed by the remaining elements of arr1 in ascending order (8, 8, 9).

Example 2:

  • Input: arr1 = [5, 5, 4, 6, 4], arr2 = [4, 5]
  • Expected Output: [4, 4, 5, 5, 6]
  • Justification: First, we arrange the common elements in the order they appear in arr2 (4, 4, 5, 5), then append the remaining elements of arr1 sorted (6).

Example 3:

  • Input: arr1 = [10, 20, 30, 20, 15, 20, 10], arr2 = [20, 10]
  • Expected Output: [20, 20, 20, 10, 10, 15, 30]
  • Justification: We follow the order in arr2 for common elements (20, 20, 20, 10, 10), then sort the rest (15, 30).

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory