LeetCode solutions

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

Read the problem on LeetCode View on GitHub

C++

Accepted on LeetCode — runtime 0ms, memory 11MB, accepted 2025-12-28.

cpp
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;
    }
};

Source