Relative Sort Array - Problem

Imagine you have two arrays: arr1 contains a mixed collection of numbers, while arr2 serves as a priority template that defines the desired ordering.

Your mission is to rearrange arr1 so that:

  • Elements that appear in arr2 come first, in the exact same relative order as they appear in arr2
  • Elements that don't appear in arr2 are placed at the end in ascending order

Think of arr2 as a VIP list - those numbers get priority placement, while the rest are sorted normally at the back of the line!

Example: If arr1 = [2,3,1,3,2,4,6,7,9,2,19] and arr2 = [2,1,4,3,9,6], the result should be [2,2,2,1,4,3,3,9,6,7,19].

Input & Output

example_1.py โ€” Basic Case
$ 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: Elements 2,1,4,3,9,6 appear first in the order specified by arr2. Each appears with its original frequency from arr1. Elements 7,19 don't appear in arr2, so they're sorted and placed at the end.
example_2.py โ€” All Elements in arr2
$ Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]
โ€บ Output: [22,28,8,6,17,44]
๐Ÿ’ก Note: Most elements follow arr2 order: 22,28,8,6. Elements 17,44 are not in arr2, so they're sorted (17 < 44) and appended at the end.
example_3.py โ€” Edge Case with Duplicates
$ Input: arr1 = [1,1,1], arr2 = [1]
โ€บ Output: [1,1,1]
๐Ÿ’ก Note: All elements in arr1 are 1, and 1 appears in arr2. So all three 1's are placed first, maintaining the relative order defined by arr2.

Constraints

  • 1 โ‰ค arr1.length, arr2.length โ‰ค 1000
  • 0 โ‰ค arr1[i], arr2[i] โ‰ค 1000
  • All elements in arr2 are distinct
  • Each element in arr2 is also in arr1

Visualization

Tap to expand
๐ŸŽช Concert Seating ArrangementOriginal Attendees (arr1): [2,3,1,3,2,4,6,7,9,2,19]Mixed crowd of VIPs and general admissionVIP Priority List (arr2): [2,1,4,3,9,6]๐ŸŒŸ VIP seating order preferenceStep 1: Count Frequencies2:31:13:24:1Step 2: VIP Section (Priority Order)22214Step 3: General Admission (Sorted)3367919๐ŸŽฏ Final Seating: [2,2,2,1,4,3,3,6,7,9,19]
Understanding the Visualization
1
Count All Attendees
Count how many tickets each person bought (frequency counting)
2
Seat VIPs First
Follow the VIP priority list order, seating all instances of each VIP
3
Sort General Admission
Arrange remaining attendees alphabetically (or numerically)
4
Final Seating Chart
VIPs in priority order, followed by sorted general admission
Key Takeaway
๐ŸŽฏ Key Insight: By treating arr2 indices as priority values and using counting sort principles, we achieve optimal performance while maintaining both priority ordering and sorted arrangement for non-priority elements.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
89.5K Views
Medium Frequency
~15 min Avg. Time
2.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