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
arr2come first, in the exact same relative order as they appear inarr2 - Elements that don't appear in
arr2are 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code