Advertisement
exmkg

Untitled

Aug 23rd, 2024
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | None | 0 0
  1. class Solution {
  2.     public int subarraySum(int[] nums, int k) {
  3.         int currentPrefixSum = 0;
  4.         int answer = 0;
  5.  
  6.         //        key       value
  7.         // Map<prefixSum, seenCount>
  8.         // seenCount is how many times prefixSum has been seen previously.
  9.         Map<Integer, Integer> prefixSumSeenCount = new HashMap<>();
  10.  
  11.         // Empty prefix => (prefixSum = 0, seenCount = 1)
  12.         prefixSumSeenCount.put(0, 1);
  13.  
  14.         // T: O(n)
  15.         // S: O(n)
  16.  
  17.         for (int i = 0; i < nums.length; i++) {
  18.             currentPrefixSum += nums[i];
  19.             // currentPrefixSum = sum(nums[0 .. i])
  20.  
  21.             // Let's add to the answer
  22.             // the count of subarrays that end at index i
  23.             // and have the sum of k.
  24.             //
  25.             // That number = seenCount of (currentPrefixSum - k)
  26.             // Why?
  27.             //
  28.             // Imagine that there is a prefix nums[0 .. j]
  29.             // that has the sum of (currentPrefixSum - k)
  30.             // that we have seen before index i. j < i
  31.             //
  32.             // If we subtract that prefix from our current prefix,
  33.             // i.e. sum(nums[0 .. i]) - sum(nums[0 .. j]), then we will have
  34.             // a subarray nums[j + 1 .. i] with a sum of
  35.             // currentPrefixSum - currentPrefixSum + k = k.
  36.             //
  37.             // Going back, we need to add seenCount of (currentPrefixSum - k)
  38.             // because there can be many prefixes with a sum of (currentPrefixSum - k)
  39.             // that we have seen and all of them when subtracted from currentPrefixSum
  40.             // produce valid subarrays that end at index i and have the sum equal to k.
  41.             //
  42.             // If we add to the answer for each i the count of subarrays that end at index i
  43.             // and have the sum of k, then we will have counted the total number of subarrays
  44.             // that have the sum of k.
  45.             answer += prefixSumSeenCount.getOrDefault(currentPrefixSum - k, 0);
  46.  
  47.             // After we have processed current prefix, we should add 1 to its seenCount.
  48.             prefixSumSeenCount.put(
  49.                 currentPrefixSum,
  50.                 prefixSumSeenCount.getOrDefault(currentPrefixSum, 0) + 1);
  51.         }
  52.        
  53.         return answer;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement