#2869
Easy Algorithms Minimum operations to collect elements
Array Hash Table Bit Manipulation
62.2% acceptance
Feb 25, 2026
210
26
You are given an array nums of positive integers and an integer k.
In one operation, you can remove the last element of the array and add it to your collection.
Return the minimum number of operations needed to collect elements 1, 2, ..., k.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
let mut collected = vec![false; (k + 1) as usize];
let mut count = 0;
let need = k as usize;
for i in (0..n).rev() {
let v = nums[i] as usize;
if v <= need && !collected[v] {
collected[v] = true;
count += 1;
}
if count == need {
return (n - i) as i32;
}
}
n as i32
}
}