Skip to main content
Back to problems
#3447
Medium Algorithms

Assign elements to groups with constraints

Array Hash Table
26.8% acceptance
Feb 25, 2026
134
12
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 at index 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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn assign_elements(groups: Vec<i32>, elements: Vec<i32>) -> Vec<i32> {
    let max_g = *groups.iter().max().unwrap() as usize;
    // For each divisor value, find smallest index in elements
    let mut div_to_idx: Vec<i32> = vec![-1; max_g + 1];
    for (j, &e) in elements.iter().enumerate() {
      let e = e as usize;
      if e > max_g { continue; }
      if div_to_idx[e] == -1 {
        // Mark all multiples of e
        let mut mult = e;
        while mult <= max_g {
          if div_to_idx[mult] == -1 { div_to_idx[mult] = j as i32; }
          mult += e;
        }
      }
    }
    groups.iter().map(|&g| div_to_idx[g as usize]).collect()
  }
}