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 INPUT arr1 (to be sorted) 2 3 1 3 2 4 6 7 9 2 19 arr2 (ordering reference) 2 1 4 3 9 6 Count HashMap Key : Count 2 : 3 3 : 2 1 : 1 4 : 1 6 : 1 7 : 1 9 : 1 19 : 1 Frequency of each element ALGORITHM STEPS 1 Build Count Map Count frequency of each element in arr1 2 Process arr2 Order For each elem in arr2, add count times to result 3 Collect Remaining Elements not in arr2 go to separate list 4 Sort and Append Sort remaining (7,19) and append to result Processing Order: arr2[0]=2 --> add 2,2,2 arr2[1]=1 --> add 1 arr2[2]=4 --> add 4 arr2[3]=3 --> add 3,3 arr2[4]=9 --> add 9 arr2[5]=6 --> add 6 FINAL RESULT Sorted Array 2 2 2 1 4 3 3 9 6 7 19 In arr2 order Remaining sorted Verification: - 2s come before 1 - OK - 1 comes before 4 - OK - 4 comes before 3s - OK - 7,19 sorted at end - OK Complexity Analysis Time: O(n + m + k log k) n=arr1, m=arr2, k=remaining Space: O(n) HashMap storage Key Insight: Use a HashMap to count frequencies in arr1, then iterate through arr2 to maintain relative order. Elements not in arr2 are collected separately, sorted, and appended at the end. The hash approach provides O(1) lookup for counts, making the algorithm efficient for large inputs. TutorialsPoint - Relative Sort Array | Hash Map Approach
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