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
Aof sizeNcontaining only positive integers and a target sumS. - Initialize two pointers,
leftandright, both initially pointing to the first element of the array. - Initialize a variable called
currentSumto 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
rightpointer until it reaches the end. - In each iteration:
- Add the value at the
rightpointer to thecurrentSum. This represents extending the current subarray by including the current element. - Check if
currentSumis equal to the target sumS. If it is, we have found a subarray with the desired sum.- In this case, add the
leftandrightindices to the result ArrayList (1-based indexing) and return the result.
- In this case, add the
- If
currentSumis less than the target sumS, move therightpointer to the next element and updatecurrentSumaccordingly. - If
currentSumis greater than the target sumS, move theleftpointer to the next element and subtract the value at theleftpointer fromcurrentSum. This represents reducing the subarray sum by excluding the element at theleftpointer. - Repeat steps 5-7 until the
rightpointer reaches the end of the array.
- Add the value at the
- If no subarray with sum
Sis 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
subarraySumfunction takes an arrayarrof integers and a target sumtargetSumas input. It returns aPaircontaining the left and right indices of the subarray with the given sum. - The function initializes the
leftandrightvariables to 0, representing the starting indices of the subarray window. - The
currentSumvariable is initialized with the value of the first element in the array,arr[0]. - The
whileloop continues until therightpointer reaches the end of the array. - Inside the loop, there’s a
whenstatement that handles three cases:- If
currentSumis equal to thetargetSum, it means we have found a subarray with the desired sum. In this case, the function returns aPaircontaining the left and right indices of the subarray, incremented by 1 to match the 1-based indexing. - If
currentSumis less than thetargetSum, we need to expand the window. Therightpointer is incremented, and the value at the newrightposition is added to thecurrentSum. - If
currentSumis greater than thetargetSum, we need to shrink the window. Theleftpointer is incremented, and the value at theleftposition is subtracted from thecurrentSum.
- If
- If the loop finishes without finding a subarray with the desired sum, the function returns a
Paircontaining-1for both the left and right indices, indicating that no such subarray exists. - The
mainfunction demonstrates the usage of thesubarraySumfunction. It initializes an example array and target sum. - The
subarraySumfunction is called with the array and target sum, and the returned left and right indices are stored in variablesleftandright. - 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.