All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1501_1600.s1590_make_sum_divisible_by_p.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g1501_1600.s1590_make_sum_divisible_by_p;

// #Medium #Array #Hash_Table #Prefix_Sum #2022_04_11_Time_56_ms_(62.20%)_Space_85.8_MB_(73.58%)

import java.util.HashMap;

/**
 * 1590 - Make Sum Divisible by P\.
 *
 * Medium
 *
 * Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty** ) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array.
 *
 * Return _the length of the smallest subarray that you need to remove, or_ `-1` _if it's impossible_.
 *
 * A **subarray** is defined as a contiguous block of elements in the array.
 *
 * **Example 1:**
 *
 * **Input:** nums = [3,1,4,2], p = 6
 *
 * **Output:** 1
 *
 * **Explanation:** The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.
 *
 * **Example 2:**
 *
 * **Input:** nums = [6,3,5,2], p = 9
 *
 * **Output:** 2
 *
 * **Explanation:** We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.
 *
 * **Example 3:**
 *
 * **Input:** nums = [1,2,3], p = 3
 *
 * **Output:** 0
 *
 * **Explanation:** Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.
 *
 * **Constraints:**
 *
 * *   1 <= nums.length <= 105
 * *   1 <= nums[i] <= 109
 * *   1 <= p <= 109
**/
public class Solution {
    public int minSubarray(int[] nums, int p) {
        HashMap hmp = new HashMap<>();
        int n = nums.length;
        int target = 0;
        int sum = 0;
        for (int num : nums) {
            target = (num + target) % p;
        }
        if (target == 0) {
            return 0;
        }
        hmp.put(0, -1);
        int ans = n;
        for (int i = 0; i < n; i++) {
            sum = (sum + nums[i]) % p;
            int key = (sum - target + p) % p;
            if (hmp.containsKey(key)) {
                ans = Math.min(ans, i - hmp.get(key));
            }
            hmp.put(sum % p, i);
        }
        if (ans < n) {
            return ans;
        } else {
            return -1;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy