Relative Sort Array

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.

30:00

Relative Sort Array
easy
Free written solution
Topics
Companies

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.

Example 1:
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]
Constraints:
  • 1≤arr1.length,arr2.length≤10001 \leq \text{arr1.length}, \text{arr2.length} \leq 1000

  • 0≤arr1[i],arr2[i]≤10000 \leq \text{arr1}[i], \text{arr2}[i] \leq 1000

  • All the elements of arr2 are distinct.

  • Each arr2[i] is in arr1.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr1":[2,3,1,3,2,4,6,7,9,2,19],"arr2":[2,1,4,3,9,6]}

Values are at most 1000, so count them in buckets instead of comparing. One pass to count, one pass to write out.

arr2 (the order to follow)

2
1
4
3
9
6

arr1 (count each value)

2
3
1
3
2
4
6
7
9
2
19

count buckets

■ in arr2 (#order)

■ leftover

0

1

#2

0

2

#1

0

3

#4

0

4

#3

0

6

#6

0

7

·

0

9

#5

0

19

·

result (0 / 11)

empty

Variables
VariableValue
len(result)0
DepthFunction Call
Stack empty
0/20