1590. Make Sum Divisible by P #659
-
Topics: Given an array of positive integers Return the length of the smallest subarray that you need to remove, or A subarray is defined as a contiguous block of elements in the array. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a combination of prefix sums and a hash table to efficiently compute the smallest subarray that needs to be removed such that the sum of the remaining elements is divisible by Key Insights:
Approach:
Let's implement this solution in PHP: 1590. Make Sum Divisible by P <?php
/**
* @param Integer[] $nums
* @param Integer $p
* @return Integer
*/
function minSubarray($nums, $p) {
// Total sum of the array
$totalSum = array_sum($nums);
$r = $totalSum % $p; // remainder when total sum is divided by p
// If remainder is 0, the total sum is already divisible by p
if ($r == 0) {
return 0;
}
$prefixSum = 0;
$minLength = PHP_INT_MAX;
$n = count($nums);
// Hash map to store the last occurrence of prefix sum % p
$prefixMap = array(0 => -1); // Initialize with 0 => -1 for cases when we find a match early
for ($i = 0; $i < $n; $i++) {
// Calculate the prefix sum
$prefixSum = ($prefixSum + $nums[$i]) % $p;
// We want to find a previous prefix sum that satisfies (prefixSum - r) % p == 0
$target = ($prefixSum - $r + $p) % $p;
if (isset($prefixMap[$target])) {
// Calculate the length of the subarray to remove
$minLength = min($minLength, $i - $prefixMap[$target]);
}
// Update the map with the current prefix sum % p and its index
$prefixMap[$prefixSum] = $i;
}
// If minLength is still INT_MAX, it's impossible to find a valid subarray
return $minLength < $n ? $minLength : -1;
}
// Test cases
$nums1 = [3, 1, 4, 2];
$p1 = 6;
echo minSubarray($nums1, $p1) . "\n"; // Output: 1
$nums2 = [6, 3, 5, 2];
$p2 = 9;
echo minSubarray($nums2, $p2) . "\n"; // Output: 2
$nums3 = [1, 2, 3];
$p3 = 3;
echo minSubarray($nums3, $p3) . "\n"; // Output: 0
?> Explanation:
Time Complexity:
Space Complexity:
|
Beta Was this translation helpful? Give feedback.
We can use a combination of prefix sums and a hash table to efficiently compute the smallest subarray that needs to be removed such that the sum of the remaining elements is divisible by
p
.Key Insights:
Prefix Sum Modulo: The sum of the entire array modulo
p
gives us the remainder when the array sum is divided byp
. If this remainder is zero, the sum is already divisible byp
, and no subarray needs to be removed. Otherwise, the goal is to remove a subarray that brings the sum modulop
to zero.Target Remainder: If the total sum modulo
p
isr
, we need to find a subarray whose sum modulop
is alsor
. Removing this subarray will result in the remaining sum being divisible byp
.Effici…