Subarray Sum Equals K - Complete Solution Guide
Subarray Sum Equals K is LeetCode problem 560, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 * 10 4 -1000 <= nums[i] <= 1000 -10 7 <= k <= 10 7
Detailed Explanation
The problem asks us to find the number of subarrays within a given array `nums` whose elements sum up to a target value `k`. A subarray is a contiguous, non-empty sequence of elements from the original array. We need to count how many such subarrays exist.
Solution Approach
The provided solutions use a prefix sum approach combined with a hash table to efficiently count the number of subarrays summing to `k`. The algorithm iterates through the `nums` array, maintaining a running `current_sum`. For each element, it checks if there exists a previous prefix sum such that the difference between the `current_sum` and `k` is equal to that previous prefix sum. This indicates that the subarray between those two prefix sum indices has a sum equal to `k`. The hash table stores the counts of each prefix sum encountered so far, allowing for O(1) lookup of previous prefix sums.
Step-by-Step Algorithm
- Step 1: Initialize a `count` to 0 to store the number of subarrays with sum `k`.
- Step 2: Initialize a `current_sum` to 0 to keep track of the running sum as we iterate through the array.
- Step 3: Create a hash table `prefix_sum_counts` to store the counts of each prefix sum encountered. Initialize `prefix_sum_counts[0] = 1` to handle cases where a subarray starting from the beginning sums to `k`.
- Step 4: Iterate through the `nums` array.
- Step 5: In each iteration, update `current_sum` by adding the current element `num`.
- Step 6: Calculate `diff = current_sum - k`. If `diff` exists as a key in `prefix_sum_counts`, it means there is a previous prefix sum such that the subarray between that prefix sum and the current index has a sum of `k`. Increment `count` by the value associated with `diff` in `prefix_sum_counts`.
- Step 7: Update the count of `current_sum` in `prefix_sum_counts`. If `current_sum` already exists, increment its count; otherwise, add it to the hash table with a count of 1.
- Step 8: After iterating through the entire array, return `count`.
Key Insights
- Insight 1: Using prefix sums can efficiently calculate the sum of any subarray in O(1) time. The sum of subarray nums[i:j] is prefix_sum[j] - prefix_sum[i-1].
- Insight 2: Employing a hash table to store the counts of prefix sums allows us to quickly determine how many times a particular prefix sum has appeared before. This lets us find subarray sums that equal `k`.
- Insight 3: Initializing the hash table with a prefix sum of 0 occurring once handles the case where a subarray starting from the beginning of the array sums to `k`.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: Array, Hash Table, Prefix Sum.
Companies
Asked at: AMD, Apollo.io, ByteDance, Capgemini, Cisco, Disney, Flipkart, Goldman Sachs, IBM, Infosys, J.P. Morgan, Morgan Stanley, Nagarro, PayPal, Quora, Ripple, Scale AI, ServiceNow, Snap, Swiggy, Tesla, Tinkoff, Walmart Labs, Yandex, tcs.