diff --git a/Subarray sum equals k.java b/Subarray sum equals k.java new file mode 100644 index 00000000..9170bc12 --- /dev/null +++ b/Subarray sum equals k.java @@ -0,0 +1,28 @@ +// TimeComplexity: O(n) +// SpaceComplexity: O(n) +// Did this code successfully run on Leetcode : yes +// Three sentences abou the solution: We count the number of subarrays whose sum equals k using a prefix-sum approach.It keeps a running sum and uses a HashMap to store how many times each prefix sum has occurred. +// If (currentSum − k) exists in the map, it means a subarray ending at the current index sums to k. +// The map is updated at each step with the current prefix sum count. Finally, we return the total number of such subarrays found. + +class Solution { + public int subarraySum(int[] nums, int k) { + int count =0; + int sum =0; + HashMap map = new HashMap<>(); + map.put(0,1); + for(int i=0; i map = new HashMap<>(); + map.put(0,-1); + for(int i=0; i set = new HashSet<>(); + int count =0; + for(int i=0; i