|
| 1 | +""" |
| 2 | +Author : Akash Singh |
| 3 | +Date : October 19, 2024 |
| 4 | +
|
| 5 | +This module finds the longest subarray with a given sum. |
| 6 | +The algorithm uses a hash map to track cumulative sums and efficiently find subarrays. |
| 7 | +""" |
| 8 | + |
| 9 | +class LongestSubarrayWithGivenSum: |
| 10 | + def __init__(self, array: list[int]) -> None: |
| 11 | + self.array = array |
| 12 | + |
| 13 | + def find_longest_subarray(self, target_sum: int) -> int: |
| 14 | + """ |
| 15 | + This function returns the length of the longest subarray |
| 16 | + that adds up to the target sum. |
| 17 | +
|
| 18 | + Runtime: O(n) |
| 19 | + Space: O(n) |
| 20 | +
|
| 21 | + >>> LongestSubarrayWithGivenSum([1, -1, 5, -2, 3]).find_longest_subarray(3) |
| 22 | + 4 |
| 23 | + >>> LongestSubarrayWithGivenSum([-2, -1, 2, 1]).find_longest_subarray(1) |
| 24 | + 2 |
| 25 | + >>> LongestSubarrayWithGivenSum([3, 1, 0, 1, 8, -2, 3]).find_longest_subarray(8) |
| 26 | + 5 |
| 27 | + >>> LongestSubarrayWithGivenSum([1, 2, 3]).find_longest_subarray(6) |
| 28 | + 3 |
| 29 | + >>> LongestSubarrayWithGivenSum([5, 1, -1, 5, -1, -2]).find_longest_subarray(4) |
| 30 | + 3 |
| 31 | + >>> LongestSubarrayWithGivenSum([2, 4, 6, 8]).find_longest_subarray(7) |
| 32 | + 0 |
| 33 | + """ |
| 34 | + prefix_sum_map = {} |
| 35 | + longest_length = 0 |
| 36 | + current_sum = 0 |
| 37 | + |
| 38 | + for i, num in enumerate(self.array): |
| 39 | + current_sum += num |
| 40 | + |
| 41 | + if current_sum == target_sum: |
| 42 | + longest_length = i + 1 # If sum equals target from index 0 |
| 43 | + |
| 44 | + if current_sum - target_sum in prefix_sum_map: |
| 45 | + longest_length = max(longest_length, i - prefix_sum_map[current_sum - target_sum]) |
| 46 | + |
| 47 | + if current_sum not in prefix_sum_map: |
| 48 | + prefix_sum_map[current_sum] = i |
| 49 | + |
| 50 | + return longest_length |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + import doctest |
| 55 | + doctest.testmod() |
0 commit comments