Maximum Size Subarray Sum Equals k — LeetCode 325 Python Solution

MediumLeetCode PremiumArrayHash TablePrefix Sum
Problem
#325
Pattern
Prefix Sum
Reading time
2 min

The problem

Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there is not one, return 0 instead.

Example

Input
nums = [1,-1,5,-2,3], k = 3
Output
4
Explanation
The subarray [1, -1, 5, -2] sums to 3 and is the longest.

Python solution

Python
class Solution:
    def maxSubArrayLen(self, nums: List[int], k: int) -> int:
        d = {0: -1}
        ans = s = 0
        for i, x in enumerate(nums):
            s += x
            if s - k in d:
                ans = max(ans, i - d[s - k])
            if s not in d:
                d[s] = i
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the array \textit{nums} auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 325. Maximum Size Subarray Sum Equals k is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 325. Maximum Size Subarray Sum Equals k?
LeetCode 325. Maximum Size Subarray Sum Equals k is rated Medium on LeetCode.
What is the time complexity of LeetCode 325. Maximum Size Subarray Sum Equals k?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 325. Maximum Size Subarray Sum Equals k?
The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
What topics does LeetCode 325. Maximum Size Subarray Sum Equals k cover?
LeetCode 325. Maximum Size Subarray Sum Equals k is tagged Array, Hash Table and Prefix Sum on LeetCode.
Is LeetCode 325. Maximum Size Subarray Sum Equals k a premium problem?
Yes. LeetCode 325. Maximum Size Subarray Sum Equals k is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview