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
start
andend
. - Maintain a variable
current_sum
to store the sum of the current subarray. - Expand the window by moving the
end
pointer to the right and updatecurrent_sum
. - If
current_sum
exceeds the target, shrink the window by moving thestart
pointer to the right untilcurrent_sum
is less than or equal to the target. - If
current_sum
equals 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.