Relative Sort Array - Problem

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.

Input & Output

Example 1 — Basic Relative Sorting
$ 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]
💡 Note: Follow arr2 order: 2 appears 3 times (2,2,2), 1 appears 1 time (1), 4 appears 1 time (4), 3 appears 2 times (3,3), 9 appears 1 time (9), 6 appears 1 time (6). Remaining elements [7,19] are sorted in ascending order.
Example 2 — No Remaining Elements
$ Input: arr1 = [2,3,1,3,2,4], arr2 = [2,1,4,3]
Output: [2,2,1,4,3,3]
💡 Note: All elements in arr1 appear in arr2. Follow arr2 order: 2 appears twice, 1 once, 4 once, 3 twice. No remaining elements to sort.
Example 3 — Edge Case with Singles
$ Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]
Output: [22,28,8,6,17,44]
💡 Note: Follow arr2 order for first 4 elements. Remaining elements [17,44] are sorted: 17 < 44, so result ends with [17,44].

Constraints

  • 1 ≤ arr1.length, arr2.length ≤ 1000
  • 0 ≤ arr1[i], arr2[i] ≤ 1000
  • All the elements of arr2 are unique
  • Each arr2[i] is in arr1

Visualization

Tap to expand
Relative Sort Array ProblemInput:arr1:231324arr2:2143Priority OrderStep 1: Priority Elements (follow arr2 order)2214332→2, 1→1, 4→4, 3→3,3Final Result:221433Priority elements in arr2 orderElements from arr2 maintain their relative order, others are sorted
Understanding the Visualization
1
Input Arrays
arr1 has all elements, arr2 defines priority order
2
Priority Ordering
Elements from arr2 come first in their specified order
3
Sort Remaining
Elements not in arr2 are sorted and appended
Key Takeaway
🎯 Key Insight: Use frequency counting to efficiently track element occurrences, then construct the result by following arr2's priority order
Asked in
Amazon 45 Google 32 Facebook 28 Microsoft 25
38.4K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen