C++/Java O(n)
This is a variation of 974. Subarray Sums Divisible by K.\n\nWe first compute modulo mod of the sum for the entire array. This modulo should be zero for the arr
This is a variation of [974. Subarray Sums Divisible by K](https://leetcode.com/problems/subarray-sums-divisible-by-k/).\n\nWe first compute modulo `mod` of the sum for the entire array. This modulo should be zero for the array to be divisible by `p`. To make it so, we need to remove a subarray, which sum modulo is a compliment `comp` to `mod`.\n\nWe use a hash map, where we track the running sum modulo, and the most recent position for that modulo. As we go through the array, we look up for a `comp` modulo in that hash map, and track the minimum window size.\n\n**C++**\n```cpp\nint minSubarray(vector<int>& nums, int p) {\n    int mod = 0, r_mod = 0, min_w = nums.size();\n    for (auto n : nums)\n        mod = (mod + n) % p;\n    if (mod == 0)\n        return 0;\n    unordered_map<int, int> pos = {{0, -1}};\n    for (int i = 0; i < nums.size(); ++i) {\n        r_mod = (r_mod + nums[i]) % p;\n        int comp = (p - mod + r_mod) % p;\n        if (pos.count(comp))\n            min_w = min(min_w, i - pos[comp]);\n        pos[r_mod] = i;\n    }\n    return min_w >= nums.size() ? -1 : min_w;\n}\n```\n**Java**\n```java\npublic int minSubarray(int[] nums, int p) {\n    int mod = 0, r_mod = 0, min_w = nums.length;\n    for (var n : nums)\n        mod = (mod + n) % p;\n    if (mod == 0)\n        return 0;\n    Map<Integer, Integer> pos = new HashMap<>();\n    pos.put(0, -1);\n    for (int i = 0; i < nums.length; ++i) {\n        r_mod = (r_mod + nums[i]) % p;\n        int comp = (p - mod + r_mod) % p;\n        if (pos.containsKey(comp))\n            min_w = Math.min(min_w, i - pos.get(comp));\n        pos.put(r_mod, i);\n    }    \n    return min_w >= nums.length ? -1 : min_w;\n}\n```
[]