Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.

A good subarray is a subarray where:

Note that:

Input: nums = [23, 2, 4, 6, 7], k = 6
Output: true
Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.
Input: nums = [23, 2, 6, 4, 7], k = 6
Output: true
Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.
Input: nums = [23,2,6,4,7], k = 13
Output: false
Explanation: There is no contiguous subarray that adds upto 13 or multiples of 13.
Constraints:

Contents

In this approach, we will first compute a prefix sum array, then to find contiguous subarray which is multiple of k is:

import java.util.Arrays; import java.util.HashMap; public class ContiguousSubArraySum { static boolean checkSubArraySum(int[] nums, int k) { HashMap<Integer, Integer> remainderToIndexMap = new HashMap<>(nums.length); remainderToIndexMap.put(0, -1); for(int i=0; i<nums.length; i++) { nums[i] = nums[i] + (i==0 ? 0 : nums[i-1]); int remainder = nums[i] % k; Integer index = remainderToIndexMap.get(remainder); if(index == null) {// remainder not exists, then we add it remainderToIndexMap.put(remainder, i); } else if (i - index >=2) { // subarray min length of 2 or more, we have found answer return true; } } return false; } public static void main(String[] args) { System.out.println(checkSubArraySum(new int[] {23,2,4,6,7}, 6)); System.out.println(checkSubArraySum(new int[] {24,2,4,6,7}, 6)); System.out.println(checkSubArraySum(new int[] {24,0}, 6)); System.out.println(checkSubArraySum(new int[] {0,0}, 6)); System.out.println(checkSubArraySum(new int[] {24}, 6)); // will produce false, since length is 1. System.out.println(checkSubArraySum(new int[] {24,1}, 6)); // will produce false, since length is 1. } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of nums array.
Space complexity: O(n), since we are creating prefix sum array with size n and a HashMap to keep the remainders and indexes.

Above implementations source code can be found at GitHub link for Java code