// Given an array[n] . Check if subarray with Sum== K exists or not
import java.util.*;
import java.lang.*;
import java.io.*;
// The main method must be in a class named "Main".
class Main {
public static boolean subarrayWithSumK(int[] arr, int k) {
int n = arr.length;
HashSet<Long> set = new HashSet<>();
// Adding 0L to the set to handle the case where the sum itself is equal to k
set.add(0L);
long psum = 0;
for (int i = 0; i < n; i++) {
psum += arr[i];
// Check if (psum - k) is present in the HashSet
if (set.contains(psum - k)) {
return true;
}
// Add psum to the HashSet
set.add(psum);
}
return false;
}
public static void main(String[] args) {
int[] arr = {1, 4, 20, 3, 10, 5};
int k = 33;
System.out.println("Result: " + subarrayWithSumK(arr, k));
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: