This problem requires add continues numbers, so the best solution is using prefix sum. Time complexity: O(n).
class Solution { public boolean checkSubarraySum(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int sum =0; for(int i=0;i<nums.length;i++){ sum+=nums[i]; int rest = sum%k; if(map.containsKey(rest)){ int index = map.get(rest); if(i-index>=2) return true; } else map.put(rest, i); //ony when map doesn't contain rest, put rest, otherwise don't update rest's index } return false; } }