2598. Smallest Missing Non-negative Integer After Operations #2302
-
|
Topics: You are given a 0-indexed integer array In one operation, you can add or subtract
The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it.
Return the maximum MEX of Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find the maximum MEX (minimum excluded non-negative integer) of an array after performing any number of operations where we can add or subtract a given value from any element. The key insight is that each element can be transformed to any non-negative integer that shares the same remainder when divided by the given value. Approach
Let's implement this solution in PHP: 2598. Smallest Missing Non-negative Integer After Operations <?php
/**
* @param Integer[] $nums
* @param Integer $value
* @return Integer
*/
function findSmallestInteger($nums, $value) {
$freq = array_fill(0, $value, 0);
foreach ($nums as $num) {
$r = $num % $value;
if ($r < 0) {
$r += $value;
}
$freq[$r]++;
}
$mex = PHP_INT_MAX;
for ($r = 0; $r < $value; $r++) {
$candidate = $r + $freq[$r] * $value;
if ($candidate < $mex) {
$mex = $candidate;
}
}
return $mex;
}
// Test cases
// Example 1
$nums = array(1, -10, 7, 13, 6, 8);
$value = 5;
echo findSmallestInteger($nums, $value) . "\n"; // Output: 4
// Example 2
$nums = array(1, -10, 7, 13, 6, 8);
$value = 7;
echo findSmallestInteger($nums, $value) . "\n"; // Output: 2
?>Explanation:
This approach efficiently leverages modular arithmetic and frequency counting to determine the smallest missing non-negative integer, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum MEX (minimum excluded non-negative integer) of an array after performing any number of operations where we can add or subtract a given value from any element. The key insight is that each element can be transformed to any non-negative integer that shares the same remainder when divided by the given value.
Approach