Untitled

 avatar
unknown
plain_text
24 days ago
1.0 kB
1
Indexable
public class SubarraySum {

    public boolean checkSubarraySum(int[] nums, int k) {
        int n = nums.length;
        int prefixSum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 0); // Base case for prefix sum 0

        for (int i = 0; i < n; i++) {
            prefixSum += nums[i];
            int prefixRemainder = prefixSum % k;

            if (map.containsKey(prefixRemainder)) {
                int leftIndex = map.get(prefixRemainder);
                if ((i+1) - leftIndex + 1 >= 2) {
                    return true;
                }
            } else {
                
                map.put(prefixRemainder, i + 1);
            }
        }

        return false;
    }

    public static void main(String[] args) {
        int[] nums = {23, 2, 4, 6, 7};
        int k = 6;
        SubarraySum solution = new SubarraySum();
        boolean result = solution.checkSubarraySum(nums, k);
        System.out.println("Result: " + result);
    }
}
Leave a Comment