#560

Subarray Sum Equals K

Medium
ArrayHash TablePrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a HashMap to store the cumulative sums and their frequencies. This allows us to efficiently find how many times a subarray sums to k by checking if the difference between the current cumulative sum and k exists in the HashMap.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a HashMap to store cumulative sums and a variable to keep track of the current sum.
  2. 2Step 2: Initialize a counter to zero to count valid subarrays.
  3. 3Step 3: Iterate through the array, updating the current sum at each step.
  4. 4Step 4: Check if (current_sum - k) exists in the HashMap. If it does, add its frequency to the counter.
  5. 5Step 5: Update the HashMap with the current sum, incrementing its frequency.
solution.py10 lines
1def subarraySum(nums, k):
2    count = 0
3    current_sum = 0
4    sum_map = {0: 1}
5    for num in nums:
6        current_sum += num
7        if (current_sum - k) in sum_map:
8            count += sum_map[current_sum - k]
9        sum_map[current_sum] = sum_map.get(current_sum, 0) + 1
10    return count

Complexity note: This complexity arises because we traverse the array once and use a HashMap to store cumulative sums, which allows for constant time lookups.

  • 1Using cumulative sums allows us to efficiently track the sum of subarrays.
  • 2HashMaps can significantly reduce the time complexity by enabling quick lookups.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.