#1122

Relative Sort Array

Easy Counting sort

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Sort arr1 so its elements follow the order given by arr2. Elements not in arr2 go at the end in ascending order. Values are 0..1000.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: order arr1 by arr2's order, leftovers ascending at the end.

Why this works: count every value, write arr2's values in its order, then the rest from 0 to 1000.

Example: arr1 [2,3,1,3,2,4,6,7,9,2,19], arr2 [2,1,4,3,9,6]

2,2,2, 1, 4, 3,3, 9, 6, then 7, 19

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using a comparator with indexOf on arr2 for every comparison — O(m) per compare.

Solve on LeetCode ↗
Complexity
  • Time: O(n + m + 1000).
  • Space: O(1001).
Topic: Sorting
🎬 Episodes 24–28: video coming soon