Advertisement

Relative Sort Array - LeetCode 1122 Solution

Relative Sort Array - Complete Solution Guide

Relative Sort Array is LeetCode problem 1122, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given two arrays arr1 and arr2 , the elements of arr2 are distinct, and all elements in arr2 are also in arr1 . Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2 . Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. 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] Example 2: Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] Output: [22,28,8,6,17,44] C

Detailed Explanation

This problem asks us to reorder `arr1` according to a very specific set of rules defined by `arr2`. The primary directive is that any numbers from `arr1` that also appear in `arr2` must maintain their *relative order* as seen in `arr2`. For instance, if `arr2` is `[X, Y, Z]`, then all occurrences of `X` from `arr1` must come before all occurrences of `Y`, which in turn must come before all occurrences of `Z`. Importantly, we must preserve the original counts of each number from `arr1`. If `2` appears three times in `arr1` and `2` is in `arr2`, all three `2`s must be in the final output, grouped together in `arr2`'s specified position.

Solution Approach

The elegant solution provided hinges on a two-phase construction process, enabled by a frequency map. First, we iterate through `arr1` to build a `counts` dictionary, meticulously recording how many times each number appears. This is our complete inventory of numbers and their quantities. In the first phase of construction, we iterate through `arr2`. For each number `num` in `arr2`, we check our `counts` dictionary. We then append `num` to our `result` list `counts[num]` times. After placing all instances of `num`, we remove `num` from `counts` to mark it as processed. This step guarantees that the `arr2`-specified ordering is strictly adhered to, and all required numbers are placed.

Step-by-Step Algorithm

  1. Count the occurrences of each element in `arr1` using a hash table or an array (counting sort).
  2. Iterate through `arr2`. For each element, add it to the result array as many times as its count in `arr1`. Update its count after each addition.
  3. Iterate through all possible elements (from 0 up to the maximum value in `arr1`). Add any remaining elements (those not in `arr2` but present in `arr1`) to the result array, ensuring they are added in ascending order.
  4. Return the result array.

Key Insights

  • **Pre-Counting for Inventory Management:** The initial pass through `arr1` to create a frequency map (`counts` dictionary) is crucial. This step effectively takes an inventory of all numbers and their exact quantities, allowing us to reconstruct the array piece by piece without losing any elements or their original multiplicity. It's the foundation for accurate reconstruction.
  • **Strategic Two-Phase Population:** The problem naturally breaks down into two distinct groups of numbers: those whose positions are dictated by `arr2`, and those that are 'leftovers'. By first iterating through `arr2` and using the frequency map to populate the `result` list, we directly implement the primary sorting rule. Crucially, removing processed elements from the `counts` map then leaves *only* the 'leftover' numbers, making their identification clean and efficient.
  • **Efficient Outlier Handling:** After the `arr2`-defined elements are placed, any remaining entries in the `counts` map represent numbers from `arr1` that did not appear in `arr2`. These 'outliers' are gathered into a `remaining` list. The final step is simply to sort this `remaining` list in ascending order and append it to the already constructed `result`. This modular approach simplifies the sorting logic, as only the outliers need a standard sort.

Complexity Analysis

Time Complexity: O(n + m + klogk)

Space Complexity: O(n)

Topics

This problem involves: Array, Hash Table, Sorting, Counting Sort.

Companies

Asked at: DE Shaw.