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 don't 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:
arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
Each arr2[i] is distinct.
Each arr2[i] is in arr1.
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.AskGif.Easy.Array
{
public class RelativeSortArraySoln
{
public int[] RelativeSortArray(int[] arr1, int[] arr2)
{
var map = new SortedDictionary<int, int>();
for (int i = 0; i < arr1.Length; i++)
{
if (map.ContainsKey(arr1[i]))
{
map[arr1[i]]++;
}
else
{
map.Add(arr1[i], 1);
}
}
var res = new int[arr1.Length];
int idx = 0;
for (int i = 0; i < arr2.Length; i++)
{
for(int j = 0; j < map[arr2[i]]; j++)
{
res[idx] = arr2[i];
idx++;
}
map.Remove(arr2[i]);
}
foreach (var item in map)
{
for (int i = 0; i < item.Value; i++)
{
res[idx] = item.Key;
idx++;
}
}
return res;
}
}
}
Time Complexity: O(n)
Space Complexity: O(n)
Unit Tests:
using LeetCode.AskGif.Easy.Array;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingUnitTest.Easy.Array
{
[TestClass]
public class RelativeSortArraySolnTests
{
[TestMethod]
public void RelativeSortArraySoln_First()
{
var arr1 = new int[] { 2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19 };
var arr2 = new int[] { 2, 1, 4, 3, 9, 6 };
var expected = new int[] { 2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19 };
var res = new RelativeSortArraySoln().RelativeSortArray(arr1, arr2);
AreEqual(expected, res);
}
[TestMethod]
public void RelativeSortArraySoln_Second()
{
var arr1 = new int[] { 28, 6, 22, 8, 44, 17 };
var arr2 = new int[] { 22, 28, 8, 6 };
var expected = new int[] { 22, 28, 8, 6, 17, 44 };
var res = new RelativeSortArraySoln().RelativeSortArray(arr1, arr2);
AreEqual(expected, res);
}
private void AreEqual(int[] res, int[] output)
{
Assert.AreEqual(res.Length, output.Length);
for (int i = 0; i < res.Length; i++)
{
Assert.AreEqual(res[i], output[i]);
}
}
}
}



