Easy explanation with diagram
\n# DRY RUN\n\n\n\n\n\n\n\n\n\n# CODE\n\n\nclass Solution {\npublic:\n    int minSubarray(vector<int>& nums, int p) {\n        int n = nums.size();\n        int
\n# **DRY RUN**\n\n![image](https://assets.leetcode.com/users/images/141e041b-a638-4dae-893d-a914fc328e93_1727939850.109283.png)\n![image](https://assets.leetcode.com/users/images/9209cec1-6c66-4fbf-9ada-be8f9b27106f_1727939850.7556942.png)\n![image](https://assets.leetcode.com/users/images/38d72008-8a4d-403a-9a25-22be41f37687_1727939850.5703537.png)\n![image](https://assets.leetcode.com/users/images/12959ba6-8ba7-41f3-8901-399cc08d78d3_1727939852.633128.png)\n![image](https://assets.leetcode.com/users/images/f9e516d3-bd3d-4679-9774-d6a24e86e98f_1727939853.8315318.png)\n![image](https://assets.leetcode.com/users/images/7d2c0aeb-415a-4361-ada4-56c9b517753b_1727939857.8316526.png)\n\n\n# **CODE**\n\n```\nclass Solution {\npublic:\n    int minSubarray(vector<int>& nums, int p) {\n        int n = nums.size();\n        int totalSum = 0;\n\n        // Step 1: Calculate total sum and target remainder\n        for (int num : nums) {\n            totalSum = (totalSum + num) % p;\n        }\n\n        int target = totalSum % p;\n        if (target == 0) return 0;  // The array is already divisible by p\n\n        // Step 2: Use a hash map to track prefix sum mod p\n        unordered_map<int, int> modMap;\n        modMap[0] =\n            -1;  // To handle the case where the whole prefix is the answer\n        int currentSum = 0, minLen = n;\n\n        // Step 3: Iterate over the array\n        for (int i = 0; i < n; ++i) {\n            currentSum = (currentSum + nums[i]) % p;\n\n            // Calculate what we need to remove\n            int needed = (currentSum - target + p) % p;\n\n            // If we have seen the needed remainder, we can consider this\n            // subarray\n            if (modMap.find(needed) != modMap.end()) {\n                minLen = min(minLen, i - modMap[needed]);\n            }\n\n            // Store the current remainder and index\n            modMap[currentSum] = i;\n        }\n\n        // Step 4: Return result\n        return minLen == n ? -1 : minLen;\n    }\n};\n```
['C++']