Using a map to find subarray with given sum (with negative numbers) : <p>Consider the following problem statement:</p>

<blockquote>
  <p>Given an unsorted array of integers, find a subarray which adds to a given number. If there are more than one subarrays with sum as the given number, print any of them.</p>
</blockquote>

<pre><code>Examples:

Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Ouptut: Sum found between indexes 2 and 4

Input: arr[] = {10, 2, -2, -20, 10}, sum = -10
Ouptut: Sum found between indexes 0 to 3

Input: arr[] = {-10, 0, 2, -2, -20, 10}, sum = 20
Ouptut: No subarray with given sum exists
</code></pre>

<p>On this <a href="http://www.geeksforgeeks.org/find-subarray-with-given-sum-in-array-of-integers/" rel="noreferrer">site</a>, the following linear time solution was suggested involving the use of a map to store the sums of the current subsets as the algorithm iterates through the array:</p>

<pre><code>// Function to print subarray with sum as given sum
void subArraySum(int arr[], int n, int sum)
{
    // create an empty map
    unordered_map&lt;int, int&gt; map;

    // Maintains sum of elements so far
    int curr_sum = 0;

    for (int i = 0; i &lt; n; i++)
    {
        // add current element to curr_sum
        curr_sum = curr_sum + arr[i];

        // if curr_sum is equal to target sum
        // we found a subarray starting from index 0
        // and ending at index i
        if (curr_sum == sum)
        {
            cout &lt;&lt; "Sum found between indexes "
                 &lt;&lt; 0 &lt;&lt; " to " &lt;&lt; i &lt;&lt; endl;
            return;
        }

        // If curr_sum - sum already exists in map
        // we have found a subarray with target sum
        if (map.find(curr_sum - sum) != map.end())
        {
            cout &lt;&lt; "Sum found between indexes "
                 &lt;&lt; map[curr_sum - sum] + 1
                 &lt;&lt; " to " &lt;&lt; i &lt;&lt; endl;
            return;
        }

        map[curr_sum] = i;
    }

    // If we reach here, then no subarray exists
    cout &lt;&lt; "No subarray with given sum exists";
}
// Driver program to test above function
int main()
{
    int arr[] = {10, 2, -2, -20, 10};
    int n = sizeof(arr)/sizeof(arr[0]);
    int sum = -10;

    subArraySum(arr, n, sum);

    return 0;
}
</code></pre>

<p>With the test case that is provided in the post, the second if statement checking whether current_sum - sum is never entered. Instead, the sum is found and is printed in the first if statement. <strong>So there a few points of confusion here</strong>:</p>

<p><strong>1: What is the purpose of looking up <code>current_sum-sum</code>  in the map?</strong></p>

<p><strong>2: In which cases would the second if statement even be entered to put the map to use in solving the problem?</strong></p>
