Description
Given an integer array nums and an integer k, return the smallest positive multiple of k that is missing from nums.
A multiple of k is any positive integer divisible by k.
Example 1:
Input: nums = [8,2,3,4,6], k = 2
Output: 10
Explanation:
The multiples of k = 2 are 2, 4, 6, 8, 10, 12... and the smallest multiple missing from nums is 10.
Example 2:
Input: nums = [1,4,7,10,15], k = 5
Output: 5
Explanation:
The multiples of k = 5 are 5, 10, 15, 20... and the smallest multiple missing from nums is 5.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 1001 <= k <= 100
Solutions
This function finds the smallest positive multiple of k that is not present in the array nums. It first converts the array into a Set so that checking whether a number exists is fast (constant time). Then it starts with num = k (the first multiple of k) and repeatedly checks: if the set contains num, it moves on to the next multiple by adding k (num += k). As soon as it reaches a multiple of k that the set does not contain, the loop stops and that value is returned — the first "missing" multiple of k.
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var missingMultiple = function(nums, k) {
const set = new Set(nums);
let num = k;
while (set.has(num)) {
num += k;
}
return num;
};