Problem
Given an array of integers and a target sum (K), find a contiguous subarray whose sum is equal to the given target sum (K). If there are multiple such subarrays, returning any one of them is sufficient. If no such subarray exists, return an empty list.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Naive
Naive approach is to generate all subarrays using nested loops, and check which subarray sum matches target. Time complexity - O(n^2)
Method 2 - Sliding Window Technique
Here is the approach:
- Use a sliding window (two-pointer) technique to find the subarray.
- Initialize two pointers
startandend. - Maintain a variable
current_sumto store the sum of the current subarray. - Expand the window by moving the
endpointer to the right and updatecurrent_sum. - If
current_sumexceeds the target, shrink the window by moving thestartpointer to the right untilcurrent_sumis less than or equal to the target. - If
current_sumequals the target, return the subarray.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), where (n) is the length of the array. Each element is processed at most twice. - 🧺 Space complexity:
O(1), for the sliding window approach, not including the space required for the output subarray.