Skip to main content
Back to problems
#3012
Medium Algorithms

Minimize length of array using operations

Array Math Greedy Number Theory
35.7% acceptance
Feb 25, 2026
197
43
You are given a 0-indexed integer array nums containing positive integers. Your task is to minimize the length of nums by performing the following operations any number of times (including zero): Select two distinct indices i and j from nums, such that nums[i] > 0 and nums[j] > 0. Insert the result of nums[i] % nums[j] at the end of nums. Delete the elements at indices i and j from nums. Return an integer denoting the minimum length of nums after performing the operation any number of times.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_array_length(nums: Vec<i32>) -> i32 {
    let min_val = *nums.iter().min().unwrap();
    let cnt = nums.iter().filter(|&&x| x == min_val).count();
    // If min appears more than once AND not divisible by anything smaller,
    // we can reduce pairs of min to 0, leaving ceil(cnt/2)
    // If any element is NOT a multiple of min, we can get 0 from that pair, leaving 1
    if nums.iter().any(|&x| x % min_val != 0) {
      return 1;
    }
    ((cnt + 1) / 2) as i32
  }
}