1217. Relative Sort Array
My accepted C++ solution to LeetCode problem 1217, Relative Sort Array, running in 0ms.
- Difficulty: Easy
- C++
- Runtime 0ms
- Memory 11MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
C++
Accepted on LeetCode — runtime 0ms, memory 11MB, accepted 2025-12-28.
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
map<int, int> count;
for (int x : arr1) count[x]++;
vector<int> result;
for (int x : arr2) {
while (count[x]-- > 0) result.push_back(x);
count.erase(x);
}
for (auto& [num, cnt] : count) {
while (cnt-- > 0) result.push_back(num);
}
return result;
}
};