C++ Simple and Short Solution, With Explanation
Idea:\nWe need the sum % p to be zero. So we have to remove the remainder of sum / p.\nIn need_to_remove we calculte the amount we need to remove from the array
**Idea:**\nWe need the sum % p to be zero. So we have to remove the remainder of sum / p.\nIn `need_to_remove` we calculte the amount we need to remove from the array.\nNow, we keep a map which holds a remainder as a key and the latest index for that remainder in a prefix sum as a value. `{remainder -> index of latest}`.\nTo find a contiguous subarray using prefix sum, at each point we save our current prefix sum in `tmp` and look if we previously saw a prefix sum that if we subtract from our current one we will get our desired sum - `tmp - need_to_remove`. (we add `p` to avoid problems with negative results).\n\n**Why does it work?**\nFor example, on regular subarray sum: \narray = [1,2,3,4,5], desired subarray sum = 7\nin each iterstion we keep in map the current running sum, so we have: \n1 -> 0, 3 -> 1, 6 -> 2, 10 -> 3\nwhen we get to this point, and we look in the map for `curr - desired` = `10 - 7 = 3`, we will find it in index 1 and we have a result.\n\n**Time Complexity:** O(n)\n**Space Complexity:** O(n)\n```\nclass Solution {\npublic:\n    int minSubarray(vector<int>& nums, int p) {\n        int tmp = 0, res = nums.size(), need_to_remove = 0;\n        for (auto num : nums) need_to_remove = (need_to_remove + num) % p;\n        if (need_to_remove == 0) return 0;\n        \n        unordered_map<int, int> pre_sum;\n        pre_sum[0] = -1;\n        \n        for (int i = 0; i < nums.size(); i++) {\n            tmp = (tmp + nums[i]) % p;\n            pre_sum[tmp] = i;\n            int rest = (tmp - need_to_remove + p) % p;\n            \n            if (pre_sum.find(rest) != pre_sum.end()) res = min(res, i - pre_sum[rest]);\n        }\n        return res >= nums.size() ? -1 : res;\n    }\n};\n```\n**Like it? please upvote!**
['C']