[Java] Play with Math and remainders!
Sum all the elements in the array. Store the mod say in a variable "total".\n\nNow you need to find the subarray with the smallest size and with a sum % p == to
Sum all the elements in the array. Store the mod say in a variable "total".\n\nNow you need to find the subarray with the smallest size and with a sum % p == total.\n\nIterate over the array, calculate running mods and check in the hashmap if there is a subarray whose sum % p == total.\n\n\n```\nclass Solution {\n    public int minSubarray(int[] nums, int p) {\n        int n = nums.length;\n        HashMap<Integer, Integer> map = new HashMap<>();\n        long sum = 0, total = 0;\n        for(int i = 0; i < n; i++) total = (total + nums[i] % p) % p;\n        for(int i = 0; i < n; i++) nums[i] = nums[i] % p;\n        if(total == 0) return 0;\n        int ans = Integer.MAX_VALUE;\n        map.put(0, -1);\n        for(int i = 0; i < n; i++) {\n            if(nums[i] % p == (int)total) return 1;\n            sum = (sum + nums[i] % p) % p;\n            if(sum >= total && map.containsKey((int)(sum - total))) ans = Math.min(ans, i - map.get((int)(sum - total)));\n            else if(sum < total) {\n                int t = (int)(total - sum);\n                t = p - t;\n                if(map.containsKey((int)(t))) ans = Math.min(ans, i - map.get((int)(t)));\n            }\n            map.put((int)sum, i);\n        }\n        return ans == Integer.MAX_VALUE || ans == n ? -1 : ans;\n    }\n}
[]