This question on LeetCode is another Slide Window problem and we can use two pointers to traverse the array to find the longest subarray whose sum equals the result of sum of elements in nums minus x. To put it simply, I drew a diagram to understand this process!
Shortest subarray (leftmost or rightmost) = nums.length - Longest subarray (SUM – X)
Question
Solution
Frist of all, we have to know how to find specific number equals the sum of the longest subarray
1 | private static int findLongestSubIntegerArr(int[] arr, int target) { |
Slide Window
- Initialize and check for Edge Cases
- Iterate through nums and every time update curSum by adding the current element
nums[right]
- If curSum exceeds target, it means that current sum is too big. So we slide the left pointer to the right by one position and minus curSum by
nums[left]
- If curSum equals target, update maxLen with the length of the current subarray, which is
right - left + 1
- After finish the loop, if maxLen is still initialized value 0, we can directly return -1. Otherwise, we return
nums.length - maxLen
as a result
1 | // Time complexity is O(n) |