Assign Elements to Groups with Constraints - Problem
You are given an integer array groups, where groups[i] represents the size of the i-th 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 at index
jcan be assigned to a groupiifgroups[i]is divisible byelements[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
-1to 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.
Input & Output
Example 1 — Basic Assignment
$
Input:
groups = [12, 8, 15], elements = [2, 3, 4, 5]
›
Output:
[0, 0, 1]
💡 Note:
Group 0 (size 12): 12 % 2 = 0, so assign element at index 0. Group 1 (size 8): 8 % 2 = 0, so assign element at index 0. Group 2 (size 15): 15 % 2 ≠ 0, but 15 % 3 = 0, so assign element at index 1.
Example 2 — No Valid Assignment
$
Input:
groups = [7, 11], elements = [2, 4, 6]
›
Output:
[-1, -1]
💡 Note:
Group 0 (size 7): 7 % 2 ≠ 0, 7 % 4 ≠ 0, 7 % 6 ≠ 0, so assign -1. Group 1 (size 11): 11 % 2 ≠ 0, 11 % 4 ≠ 0, 11 % 6 ≠ 0, so assign -1.
Example 3 — Same Element for Multiple Groups
$
Input:
groups = [6, 12, 18], elements = [3, 9]
›
Output:
[0, 0, 0]
💡 Note:
All groups are divisible by element 3 (at index 0): 6 % 3 = 0, 12 % 3 = 0, 18 % 3 = 0. Since we pick the smallest index, all groups get assigned element at index 0.
Constraints
- 1 ≤ groups.length, elements.length ≤ 103
- 1 ≤ groups[i] ≤ 109
- 0 ≤ elements[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Groups array with sizes and elements array with values
2
Process
For each group, find first element that divides the group size
3
Output
Array of element indices or -1 for each group
Key Takeaway
🎯 Key Insight: Always assign the first (smallest index) element that satisfies the divisibility constraint for each group
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code