Problem 1122

Abstract / Summary

Arrange one array to match the order of another while placing unmatched items in ascending order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1122.py

class Solution:
    def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
        order = { value: pos for pos, value in enumerate(arr2) }
        return sorted(arr1, key = lambda x : order[x] if x in order else 10_000 + x)
4 lines | 250 bytes | submitted November 7, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 75% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Counting Sort
  • Hash Table
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method relativeSortArray. The method receives two integer lists, arr1 and arr2, and returns a new list where the elements of arr1 are ordered according to the sequence defined by arr2. Elements that do not appear in arr2 are placed after the ordered segment and are sorted in ascending numeric order.

Key Steps

The algorithm proceeds in two distinct phases.

The first phase constructs a mapping from each value in arr2 to its positional index. This mapping enables constant-time lookup of the desired order for any element that belongs to arr2.

order = { value: pos for pos, value in enumerate(arr2) }

The second phase sorts arr1 using Python’s built-in sorted function with a custom key function. The key function checks whether the current element exists in the order dictionary. If it does, the key is the stored position; otherwise, the key is a large offset (10_000) plus the element’s own value. This scheme guarantees that all elements not present in arr2 receive keys larger than any legitimate position from arr2, causing them to appear after the ordered segment while preserving their natural numeric order.

return sorted(arr1, key = lambda x : order[x] if x in order else 10_000 + x)

Edge Cases Handled

When arr2 is empty, the dictionary order is empty, so every element of arr1 falls into the “else” branch of the key function. The resulting list is simply a sorted version of arr1, satisfying the requirement that all elements be placed after the (non-existent) ordered segment.

If arr1 is empty, the sorted call receives an empty iterable and returns an empty list, which is the correct output for an empty input.

Duplicate values in arr1 are naturally handled because the key function is applied to each occurrence independently. Elements that appear multiple times in arr2 are not a concern; order stores only the first position encountered during enumeration, and any subsequent duplicates in arr2 are ignored, which aligns with the intended ordering semantics.

Negative numbers or numbers larger than the offset (10_000) are also accommodated. For any value not in order, the key becomes 10_000 + x. Since all legitimate positions from arr2 are non-negative and less than the length of arr2, the offset ensures that the computed key is always greater than any position key, regardless of the sign or magnitude of x. Consequently, such values are correctly placed after the ordered segment and sorted among themselves by their natural value.

Performance Optimizations

The construction of the order dictionary uses a dictionary comprehension combined with enumerate, yielding a single pass over arr2 and producing a hash-based lookup table. This enables O(1) average-time retrieval of the ordering index for each element during sorting.

The sorting step leverages Python’s highly optimized Timsort algorithm, which is adaptive and stable. By providing a key function that returns simple integer values, the sort avoids expensive custom comparison logic. The key function itself performs a single dictionary membership test followed by a direct dictionary access or a constant-time arithmetic operation, both of which are inexpensive.

The use of a fixed large offset (10_000) eliminates the need for a secondary sorting pass for elements not present in arr2. Instead, those elements are automatically ordered by their numeric value within the same sorting operation, reducing overall work and memory overhead.

Overall, the solution combines a linear-time preprocessing step with a single, efficient sorting pass, resulting in a concise and performant implementation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having two different boxes of numbered blocks. The first box has a big messy pile of blocks, and the second box is a special list that tells you exactly which order those blocks should go if they were lined up on a shelf.

The code starts by making a quick checklist so it knows exactly where each block from the second box belongs. It looks at the second box and remembers the position of every number.

Next, it looks at the messy pile in the first box and starts picking them up one by one to put them in order. For the blocks that have a spot on the special list, it puts them in the exact order decided by that list. If a block is not on the special list, it acts like a little explorer and goes to the very end of the line, keeping its own numerical value to decide where it fits relative to the other extra blocks. Once every block has been looked at, they are all lined up perfectly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.04 | σ = 0.96

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go Swift TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
shreymehul C#
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Python, Swift, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
shreymehul C#
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
31 links | 19 authors | 9 languages

Videos

11 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

8 solutions   November 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality