[LeetCode] Assign Elements to Groups with Constraints

3447. Assign Elements to Groups with Constraints

You are given an integer array groups, where groups[i] represents the size of the ith group. You are also given an integer array elements.

Your task is to assign one element to each group based on the following rules:

  • An element j can be assigned to a group i if groups[i] is divisible by elements[j].
  • If there are multiple elements that can be assigned, assign the element with the smallest index j.
  • If no element satisfies the condition for a group, assign -1 to that group.

Return an integer array assigned, where assigned[i] is the index of the element chosen for group i, or -1 if no suitable element exists.

Note: An element may be assigned to more than one group.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
vector<int> assignElements(vector<int>& groups, vector<int>& elements) {
unordered_set<int> E,G(begin(groups), end(groups));
vector<vector<int>> rgroups(101010);
vector<int> res(groups.size(), -1);
for(int i = 0; i < groups.size(); i++) rgroups[groups[i]].push_back(i);
for(int i = 0; i < elements.size(); i++) {
int e = elements[i];
if(E.count(e)) continue;
for(int j = e; j <= 1e5; j += e) {
if(!G.count(j)) continue;
while(rgroups[j].size()) {
auto idx = rgroups[j].back(); rgroups[j].pop_back();
res[idx] = i;
}
G.erase(j);
}
E.insert(e);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/02/09/PS/LeetCode/assign-elements-to-groups-with-constraints/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.