Taro Logo

Subarray Sum Equals K

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+33
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.7K views
Topics:
ArraysSliding WindowsDynamic Programming

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [1,1,1], k = 2
Output: 2

Example 2:

Input: nums = [1,2,3], k = 3
Output: 2

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -1000 <= nums[i] <= 1000
  • -107 <= k <= 107

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the elements in the input array `nums` be negative, zero, or are they strictly positive integers?
  2. What should the function return if no such continuous subarray is found (e.g., return `0`)?
  3. Can the input array `nums` be empty or `null`, and if so, what should be expected as the output?
  4. Are the elements guaranteed to fit within standard integer limits, or could the running sums cause integer overflow?
  5. Is the target `k` guaranteed to be an integer, and can it be negative, zero, or positive?

Brute Force Solution

Approach

Imagine you have a long row of numbered boxes and you want to find every possible consecutive group of boxes whose numbers add up to a specific target sum. The brute force approach simply investigates every single possible starting point and ending point to check every combination one by one.

Here's how the algorithm would work step-by-step:

  1. Begin by picking the very first box in the row as your starting point.
  2. Look at just that single box and check if its number matches your target sum.
  3. Next, expand your selection to include the very next box right beside it, adding their numbers together to see if the new total matches your target sum.
  4. Keep adding boxes one by one to your current group, checking the total each time, until you reach the very end of the row.
  5. Once you have checked every possible group starting from the first box, move your starting point to the second box in the row.
  6. Repeat the entire process of growing the group box by box and checking the total sum starting from this new position.
  7. Continue this exact process for every single box in the row, making sure you have tested every possible continuous section of boxes.
  8. Keep a running count of every single time a group of boxes adds up to your exact target sum so you can give the final total at the end.

Code Implementation

def subarray_sum(numbers, target_sum):
    matching_subarrays_count = 0
    
    # Iterate through every possible starting position to ensure all subarrays are tested
    for start_index in range(len(numbers)):
        current_subarray_sum = 0
        
        # Expand the subarray one box at a time to check the cumulative sum sequentially
        for end_index in range(start_index, len(numbers)):
            current_subarray_sum += numbers[end_index]
            
            # Compare the accumulated sum against the target to count valid subarrays
            if current_subarray_sum == target_sum:
                matching_subarrays_count += 1
                
    return matching_subarrays_count

Big(O) Analysis

Time Complexity
O(n²) – For each of the n boxes in the row, we use a nested loop to test every possible consecutive ending point moving toward the end of the array. The first box requires checking up to n subsequent positions, the second box checks n-1 positions, and this linear reduction continues down to a single check for the final box. This pattern totals approximately n * (n + 1) / 2 total subarray sum checks across all starting positions. Dropping constants and lower-order terms, the overall time complexity simplifies to O(n²).
Space Complexity
O(N) – To implement the optimal approach implied by the process, we use a hash map to store the frequencies of prefix sums encountered as we iterate through the N elements. In the worst-case scenario, every prefix sum up to N will be distinct, meaning the hash map will store up to N key-value pairs. Consequently, the extra memory required scales linearly with the input size N. Therefore, the auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

Instead of checking every single possible grouping of numbers, the optimal approach keeps a running total of the numbers as we encounter them. By keeping track of how often each running total has appeared in the past, we can instantly spot hidden sections that add up to our target.

Here's how the algorithm would work step-by-step:

  1. Imagine walking along a path and keeping a running tally of all the numbers you have stepped on so far.
  2. At every step, figure out what past running tally you would need to have seen earlier so that the difference between that past tally and your current tally equals your target number.
  3. Check your memory to see if you have encountered that specific past tally before, and if so, grab how many times it happened.
  4. Add those occurrences to your running count of successful matches.
  5. Record your current running tally into your memory so future steps can look back at it.
  6. Continue this process until you reach the end of the path, giving you the total number of matching sections without ever having to re-examine past steps from scratch.

Code Implementation

def subarray_sum(nums, target_k):
    running_tally = 0
    matching_sections_count = 0
    tally_frequency_map = {0: 1}

    # Check if a past tally exists whose difference with current tally equals target.
    for number in nums:
        running_tally += number
        needed_past_tally = running_tally - target_k

        if needed_past_tally in tally_frequency_map:
            matching_sections_count += tally_frequency_map[needed_past_tally]

        # Record current running tally into memory so future steps can look back at it.
        if running_tally in tally_frequency_map:
            tally_frequency_map[running_tally] += 1
        else:
            tally_frequency_map[running_tally] = 1

    return matching_sections_count

Big(O) Analysis

Time Complexity
O(n) – As we walk along the array of size n, we perform a single pass from start to finish. At each of the n steps, we calculate the current running sum and perform a constant time hash map lookup and insertion to check our memory. Since we never re-examine past steps from scratch and each step involves only O(1) operations, the total operations scale linearly as n multiplied by 1, which simplifies to O(n).
Space Complexity
O(N) – The space complexity is driven by the hash map used to store the frequency of each running total as we iterate through the input array of size N. In the worst-case scenario, every prefix sum is unique, causing the hash map to grow linearly and store up to N distinct entries. Therefore, the extra memory required scales directly with the input size N, simplifying to Big O of N.

Edge Cases

Empty array nums with any value of k
How to Handle:
The prefix sum map initialized with zero count ensures the loop returns zero without throwing errors.
Array containing a single element equal to k
How to Handle:
The running prefix sum equals k and the pre-existing base entry of {0: 1} increments the count to one.
Array containing a single element not equal to k
How to Handle:
The running prefix sum does not match k minus any previous sum, resulting in a return value of zero.
Array with negative numbers and zeros mixed in
How to Handle:
Prefix sum logic naturally handles negative increments and zero values because sums are not strictly increasing.
Multiple subarrays sharing overlapping ranges summing to k
How to Handle:
Storing prefix sum frequencies in a hash map accurately counts every valid starting point for each ending point.
No subarray sums up to k
How to Handle:
The total count remains at its initial value of zero and returns correctly after traversing the array.
Maximum sized inputs up to the constraints limit
How to Handle:
An O(n) linear scan using a hash map processes the entire array efficiently within standard time limits.
Large cumulative sums causing potential integer overflow
How to Handle:
Using standard 64-bit integer types for the running sum prevents overflow issues during extreme summation.
0/75 completed