Introduction

I'll demonstrate how to locate a continuous subarray in an integer array that precisely adds up to a specified amount in this blog. This is a common issue that comes up frequently in competitive programming and coding interviews. It's a fantastic method to practice effective searching strategies and get familiar with arrays.

I'll show you how to handle large arrays quickly and easily using the sliding window technique, which operates in linear time. I'll walk through the process, give a clear sample of C# code, and highlight significant edge cases to be aware of along the way.

Problem Statement

Determine the beginning and ending indices of a continuous subarray whose sum equals the goal sum, given an array of positive integers and the target sum. Returning any one of these subarrays is acceptable if there are several. Indicate it appropriately if there isn't a subarray of that kind.

Approach Explanation (Sliding Window)

Since the array only contains positive values, we can design a sliding window that tracks a running sum using two pointers, start and finish.

C# Code Implementation

using System;

class SubarrayWithGivenSum
{
    public static void FindSubarray(int[] arr, int targetSum)
    {
        int start = 0, currentSum = 0;

        for (int end = 0; end < arr.Length; end++)
        {
            currentSum += arr[end];

            // Shrink the window from the left if currentSum is greater than targetSum
            while (currentSum > targetSum && start < end)
            {
                currentSum -= arr[start];
                start++;
            }

            // Check if currentSum matches the targetSum
            if (currentSum == targetSum)
            {
                Console.WriteLine($"Subarray found from index {start} to {end}");
                return;
            }
        }

        Console.WriteLine("No subarray with the given sum found.");
    }

    static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 7, 5 };
        int targetSum = 12;

        FindSubarray(arr, targetSum);
    }
}

Sample Output

Subarray in C#

Time & Space Complexity

Edge Cases to Keep in Mind