The “Subarray with Given Sum” problem involves finding a subarray within an unsorted array where the sum of its elements is equal to a given target sum. The problem requires returning the left and right indices (1-based indexing) of the subarray.
Here’s a step-by-step explanation of how to solve the problem:
- We are given an unsorted array
A
of sizeN
containing only positive integers and a target sumS
. - Initialize two pointers,
left
andright
, both initially pointing to the first element of the array. - Initialize a variable called
currentSum
to store the sum of the current subarray. Set its initial value to the first element of the array,A[0]
. - Start iterating through the array using the
right
pointer until it reaches the end. - In each iteration:
- Add the value at the
right
pointer to thecurrentSum
. This represents extending the current subarray by including the current element. - Check if
currentSum
is equal to the target sumS
. If it is, we have found a subarray with the desired sum.- In this case, add the
left
andright
indices to the result ArrayList (1-based indexing) and return the result.
- In this case, add the
- If
currentSum
is less than the target sumS
, move theright
pointer to the next element and updatecurrentSum
accordingly. - If
currentSum
is greater than the target sumS
, move theleft
pointer to the next element and subtract the value at theleft
pointer fromcurrentSum
. This represents reducing the subarray sum by excluding the element at theleft
pointer. - Repeat steps 5-7 until the
right
pointer reaches the end of the array.
- Add the value at the
- If no subarray with sum
S
is found, return an ArrayList containing a single element -1 to indicate that no such subarray exists.
By using the sliding window technique, we maintain a window that slides through the array, adjusting its size based on the comparison of the current sum with the target sum. This approach has a time complexity of O(N) since we only iterate through the array once.
Consider the following array: [1, 2, 3, 7, 5]
and the target sum S = 12
.
Array: [1, 2, 3, 7, 5]
Indices: 1 2 3 4 5
Current Window: [2, 3, 7]
Current Sum: 12
Finally, the current sum becomes equal to the target sum (12 == 12
). We have found a subarray that adds up to the given sum. The left index is 2, and the right index is 4. So, the subarray with the sum 12 is [2, 3, 7]
.Therefore, the expected output for this example would be 2 4
The Kotlin code for the “Subarray with Given Sum” problem:
fun subarraySum(arr: IntArray, targetSum: Int): Pair<Int, Int> {
var left = 0
var right = 0
var currentSum = arr[0]
while (right < arr.size) {
when {
currentSum == targetSum -> return Pair(left + 1, right + 1)
currentSum < targetSum -> {
right++
if (right < arr.size) {
currentSum += arr[right]
}
}
else -> {
currentSum -= arr[left]
left++
}
}
}
return Pair(-1, -1)
}
fun main() {
val arr = intArrayOf(1, 2, 3, 7, 5)
val targetSum = 12
val (left, right) = subarraySum(arr, targetSum)
if (left == -1 && right == -1) {
println("No subarray with sum $targetSum found.")
} else {
println("Subarray with sum $targetSum found at indices: $left to $right")
}
}
- The
subarraySum
function takes an arrayarr
of integers and a target sumtargetSum
as input. It returns aPair
containing the left and right indices of the subarray with the given sum. - The function initializes the
left
andright
variables to 0, representing the starting indices of the subarray window. - The
currentSum
variable is initialized with the value of the first element in the array,arr[0]
. - The
while
loop continues until theright
pointer reaches the end of the array. - Inside the loop, there’s a
when
statement that handles three cases:- If
currentSum
is equal to thetargetSum
, it means we have found a subarray with the desired sum. In this case, the function returns aPair
containing the left and right indices of the subarray, incremented by 1 to match the 1-based indexing. - If
currentSum
is less than thetargetSum
, we need to expand the window. Theright
pointer is incremented, and the value at the newright
position is added to thecurrentSum
. - If
currentSum
is greater than thetargetSum
, we need to shrink the window. Theleft
pointer is incremented, and the value at theleft
position is subtracted from thecurrentSum
.
- If
- If the loop finishes without finding a subarray with the desired sum, the function returns a
Pair
containing-1
for both the left and right indices, indicating that no such subarray exists. - The
main
function demonstrates the usage of thesubarraySum
function. It initializes an example array and target sum. - The
subarraySum
function is called with the array and target sum, and the returned left and right indices are stored in variablesleft
andright
. - If the left and right indices are both
-1
, it means no subarray with the sum exists, and an appropriate message is printed. - If the left and right indices are not
-1
, it means a subarray with the sum was found, and a message displaying the indices is printed.
The time complexity of the code is O(N), where N is the length of the input array.
The while loop iterates through the array once, with both the left and right pointers moving at most N steps. Therefore, the time complexity of the code is linear with respect to the size of the input array.
The space complexity of the code is O(1), which means it uses constant space. The space requirements do not depend on the size of the input array. The code only uses a few integer variables to keep track of indices and the current sum, so the space complexity remains constant regardless of the input size.