15. Subarray Range with Given Sum

The problem can be found at the following link: Question Link

Problem Description

Given an unsorted array of integers arr[], and a target sum tar, determine the number of subarrays whose elements sum up to the target value.

Example:

Input: arr[] = [10, 2, -2, -20, 10] tar = -10

Output: 3

Explanation: Subarrays with sum -10 are:

  • [10, 2, -2, -20]

  • [2, -2, -20, 10]

  • [-20, 10]

Constraints:

  • 1 <= arr.size() <= 10^6

  • -10^5 <= arr[i] <= 10^5

  • -10^5 <= tar <= 10^5


My Approach

  1. Prefix Sum and Hashmap:

    • The core idea is to use a prefix sum array and a hashmap (or dictionary) to store the frequency of sums encountered so far.

    • Iterate through the array, calculating the cumulative sum as we go, and check if there is a prefix sum that, when subtracted from the current cumulative sum, equals the target tar.

    • If a valid prefix sum is found, it indicates a subarray that sums to the target, so we increment the count.

  2. Hashmap Optimization:

    • The hashmap stores the frequency of each prefix sum encountered.

    • For each element in the array, we check if the difference between the current sum and the target sum exists in the hashmap.

    • If it does, the value in the hashmap indicates how many subarrays with the target sum can be formed up to this point.

  3. Time and Space Efficiency:

    • This approach ensures we only traverse the array once, maintaining a time complexity of O(n).

    • The auxiliary space is O(n) due to the hashmap storing the prefix sums.


Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), as we traverse the array once and perform constant-time operations (hashmap lookups and updates) for each element.

  • Expected Auxiliary Space Complexity: O(n), due to the storage of the prefix sum frequencies in a hashmap.


Code (C++)


Code (Java)


Code (Python)


Contribution and Support

For discussions, questions, or doubts related to this solution, please visit my LinkedIn:- Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.

⭐ Star this repository if you find it helpful or intriguing! ⭐


📍Visitor Count

Last updated