Grokking the Coding Interview: Patterns for Coding Questions
Vote
0% completed
Maximum Size Subarray Sum Equals k (medium)
Problem Statement
Given an array of integers nums and an integer k, find the length of the longest subarray that sums to k. If no such subarray exists, return 0.
Examples
Example 1:
- Input:
nums = [1, 2, 3, -2, 5], k = 5 - Output:
2 - Explanation: The longest subarray with a sum of
5is[2, 3], which has a length of2.
Example 2:
- Input:
nums = [-2, -1, 2, 1], k = 1 - Output:
2 - Explanation: The longest subarray with a sum of
1is[-1, 2], which has a length of2.
Example 3:
- Input:
.....
.....
.....
Like the course? Get enrolled and start learning!
Mohammed Dh Abbas
· 2 years ago
class Solution: def maxSubArrayLen(self, nums, k): sum_lookup = {} acc_sum = 0 # accumulated sum length = 0 for index, num in enumerate(nums): acc_sum += num sum_lookup[acc_sum] = index # if the sub array starts from the first location in nums array we use the length up to that point # example [1, -1, 0, 2, 3], K = 2 answer is 4 if acc_sum == k: length = index + 1 # search "O(1) using hashmap" for any accumulated sum that is = acc_sum - k then measure the difference of indexes length # example [3, 4, 7, 2, -3, 1, 4, 2], k = 7 answer is 4 elif acc_sum - k in sum_lookup: len