325. Maximum Size Subarray Sum Equals k
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the maximum length of a contiguous subarray in a given array nums that sums up to a target value k. A brute-force approach of checking every possible subarray would be O(n²), which is too slow given the constraint n <= 2 * 10^5. This suggests a more efficient approach, likely O(n), is needed.
Solution
Maximum Size Subarray Sum Equals k in Python
class Solution:
def maxSubArrayLen(self, nums: List[int], k: int) -> int:
# map to store the first occurrence of a prefix sum
# {prefix_sum: index}
prefix_sum_map = {0: -1}
current_sum = 0
max_length = 0
for i, num in enumerate(nums):
# Update the current prefix sum
current_sum += num
# Calculate the target prefix sum we need to find
target = current_sum - k
# Check if the target prefix sum exists in the map
if target in prefix_sum_map:
# If it exists, we found a subarray that sums to k.
# The length is the current index minus the index of the target prefix sum.
max_length = max(max_length, i - prefix_sum_map[target])
# If the current prefix sum is not in the map, add it.
# We only store the first occurrence to maximize the subarray length.
if current_sum not in prefix_sum_map:
prefix_sum_map[current_sum] = i
return max_length
Maximum Size Subarray Sum Equals k in Java
class Solution {
public int maxSubArrayLen(int[] nums, int k) {
// map to store the first occurrence of a prefix sum
// {prefix_sum: index}
Map<Long, Integer> prefixSumMap = new HashMap<>();
long currentSum = 0;
int maxLength = 0;
// Initialize the map with a prefix sum of 0 at index -1.
// This handles cases where the subarray starts from index 0.
prefixSumMap.put(0L, -1);
for (int i = 0; i < nums.length; i++) {
// Update the current prefix sum. Use long to prevent overflow.
currentSum += nums[i];
// Calculate the target prefix sum we need to find
long target = currentSum - k;
// Check if the target prefix sum exists in the map
if (prefixSumMap.containsKey(target)) {
// If it exists, we found a subarray that sums to k.
// The length is the current index minus the index of the target prefix sum.
maxLength = Math.max(maxLength, i - prefixSumMap.get(target));
}
// If the current prefix sum is not in the map, add it.
// We only store the first occurrence to maximize the subarray length.
if (!prefixSumMap.containsKey(currentSum)) {
prefixSumMap.put(currentSum, i);
}
}
return maxLength;
}
}
Maximum Size Subarray Sum Equals k in C++
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
// map to store the first occurrence of a prefix sum
// {prefix_sum: index}
unordered_map<long long, int> prefixSumMap;
long long currentSum = 0;
int maxLength = 0;
// Initialize the map with a prefix sum of 0 at index -1.
// This handles cases where the subarray starts from index 0.
prefixSumMap[0] = -1;
for (int i = 0; i < nums.size(); ++i) {
// Update the current prefix sum
currentSum += nums[i];
// Calculate the target prefix sum we need to find
long long target = currentSum - k;
// Check if the target prefix sum exists in the map
if (prefixSumMap.count(target)) {
// If it exists, we found a subarray that sums to k.
// The length is the current index minus the index of the target prefix sum.
maxLength = max(maxLength, i - prefixSumMap[target]);
}
// If the current prefix sum is not in the map, add it.
// We only store the first occurrence to maximize the subarray length.
if (prefixSumMap.find(currentSum) == prefixSumMap.end()) {
prefixSumMap[currentSum] = i;
}
}
return maxLength;
}
};
Maximum Size Subarray Sum Equals k in TypeScript
function maxSubArrayLen(nums: number[], k: number): number {
// map to store the first occurrence of a prefix sum
// {prefix_sum: index}
const prefixSumMap = new Map<number, number>();
let currentSum = 0;
let maxLength = 0;
// Initialize the map with a prefix sum of 0 at index -1.
// This handles cases where the subarray starts from index 0.
prefixSumMap.set(0, -1);
for (let i = 0; i < nums.length; i++) {
// Update the current prefix sum.
// JavaScript numbers are 64-bit floats, safe for these constraints.
currentSum += nums[i];
// Calculate the target prefix sum we need to find
const target = currentSum - k;
// Check if the target prefix sum exists in the map
if (prefixSumMap.has(target)) {
// If it exists, we found a subarray that sums to k.
// The length is the current index minus the index of the target prefix sum.
maxLength = Math.max(maxLength, i - prefixSumMap.get(target)!);
}
// If the current prefix sum is not in the map, add it.
// We only store the first occurrence to maximize the subarray length.
if (!prefixSumMap.has(currentSum)) {
prefixSumMap.set(currentSum, i);
}
}
return maxLength;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.