Leetcode 1122: Relative Sort Array

grid47
grid47
Exploring patterns and algorithms
Jul 17, 2024 6 min read

You are given two arrays: arr1 and arr2. The elements of arr2 are distinct, and all elements in arr2 exist in arr1. The task is to sort the elements of arr1 such that the relative ordering of elements in arr1 matches the order of elements in arr2. Elements in arr1 that are not present in arr2 should be placed at the end of arr1 in ascending order.
Problem
Approach
Steps
Complexity
Input: The input consists of two integer arrays, `arr1` and `arr2`. The length of `arr1` and `arr2` can range from 1 to 1000, and all elements in `arr2` are distinct and exist in `arr1`.
Example: Input: arr1 = [5, 6, 1, 3, 9, 1, 7], arr2 = [3, 1, 7]
Constraints:
• 1 <= arr1.length, arr2.length <= 1000
• 0 <= arr1[i], arr2[i] <= 1000
• All elements of arr2 are distinct.
• Each element of arr2 is present in arr1.
Output: The output should be an array where the elements in `arr1` are sorted such that the relative order of elements from `arr2` is preserved, and elements not in `arr2` appear at the end of the array in ascending order.
Example: Output: [3, 1, 7, 5, 6, 9]
Constraints:
• The elements in arr1 should be sorted in the specified order as per arr2.
Goal: Sort the elements of `arr1` based on their position in `arr2`, and place the remaining elements at the end in ascending order.
Steps:
• Create a mapping for the elements in `arr2` to track their order.
• Sort the elements of `arr1` by using this mapping to prioritize the order of `arr2` elements.
• For elements not in `arr2`, sort them in ascending order and append them at the end of the array.
Goal: Ensure that the elements of `arr1` are reordered such that those in `arr2` appear first in the order given, followed by the remaining elements sorted in ascending order.
Steps:
• The algorithm must preserve the relative order of `arr1` as defined by `arr2`.
Assumptions:
• Each element of `arr2` exists at least once in `arr1`.
• Elements of `arr1` that are not present in `arr2` should be sorted and placed at the end.
Input: Input: arr1 = [4, 3, 1, 2], arr2 = [3, 1]
Explanation: In this case, the output should be `[3, 1, 2, 4]` because the order of elements in `arr1` matching `arr2` (3 first, then 1) is preserved, and the remaining elements (2, 4) are placed at the end in ascending order.

Input: Input: arr1 = [10, 5, 7, 6], arr2 = [5, 6]
Explanation: The output should be `[5, 6, 7, 10]` as `arr1` elements in `arr2` (5, 6) are placed first, and the remaining elements (7, 10) are sorted and placed at the end.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus