codekofi
← All problems

Problem 60

Medium

1 · Worked examples

0 / 4

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 4 outputs correctly.

The accepted solution

1vector<int> solution(const vector<int>& nums, int k) {
2
3 unordered_map<int, int> count;
4
5 for (int x : nums) {
6 count[x]++;
7 }
8
9 int n = nums.size();
10 vector<vector<int>> byCount(n + 1);
11
12 for (const auto& [value, c] : count) {
13 byCount[c].push_back(value);
14 }
15
16 vector<int> ans;
17
18 for (int c = n; c >= 1; c--) {
19 for (int value : byCount[c]) {
20
21 ans.push_back(value);
22
23 if ((int)ans.size() == k) {
24 return ans;
25 }
26 }
27 }
28
29 return ans;
30}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.