Start learning free

LESSON 234 OF 409 · PARTIAL SUMS #2

Subarray of Given Sum II in C++ with O(n) Time Complexity

Practice O(n) Read the full explanation

Given an array of integers and a number target, find a continuous subarray whose sum is equal to target.

Return the start and end indices denoting this subarray, or -1 and -1 if there is none. If there are multiple solutions, you can return any of them.


Example:

Input: nums = [1, 1, 5, 2, 1, 3, 10, 2, 1], target = 21
Output: [2, 6]
Explanation: 5 + 2 + 1 + 3 + 10 = 21

Notes:

1. The array can consist of positive and negative numbers.

2. Your algorithm should run in O(n) time and use O(n) extra space.


Video Solution - Live Mock Coding Interview:
STEP 1 OF 10
    Ctrl + Enter to check

    C++ · PARTIAL SUMS #2

    Subarray Of Given Sum in C++, explained

    Understanding the Problem

    The core challenge of this problem is to find a continuous subarray within the given array that sums up to the target value. This problem is significant in various applications such as financial analysis, where one might need to find a period with a specific sum of transactions.

    Potential pitfalls include handling negative numbers and ensuring the solution runs efficiently within the given constraints.

    Approach

    To solve this problem, we can use a sliding window approach combined with a hash map to keep track of the cumulative sums. This allows us to find the subarray in O(n) time complexity.

    Naive Solution

    A naive solution would involve checking all possible subarrays and their sums, which would result in O(n^2) time complexity. This is not optimal for large arrays.

    Optimized Solution

    The optimized solution involves using a hash map to store the cumulative sum up to each index. By doing this, we can quickly check if there is a subarray that sums to the target by looking for the difference between the current cumulative sum and the target in the hash map.

    Algorithm

    1. Initialize a hash map to store the cumulative sum and its corresponding index.

    2. Iterate through the array, updating the cumulative sum.

    3. For each element, check if the cumulative sum minus the target exists in the hash map.

    4. If it exists, return the indices. Otherwise, store the cumulative sum and its index in the hash map.

    Code Implementation

    
    #include <iostream>
    #include <unordered_map>
    #include <vector>
    
    std::vector<int> subarraySum(std::vector<int> &nums, int target) {
        std::unordered_map<int, int> sumMap; // To store cumulative sum and its index
        int cumulativeSum = 0;
        sumMap[0] = -1; // To handle the case when subarray starts from index 0
    
        for (int i = 0; i < nums.size(); ++i) {
            cumulativeSum += nums[i];
    
            // Check if (cumulativeSum - target) exists in the map
            if (sumMap.find(cumulativeSum - target) != sumMap.end()) {
                return {sumMap[cumulativeSum - target] + 1, i};
            }
    
            // Store the cumulative sum with its index
            sumMap[cumulativeSum] = i;
        }
    
        return {}; // Return an empty vector if no subarray is found
    }
    
    int main() {
        std::vector<int> nums = {1, 1, 5, 2, 1, 3, 10, 2, 1};
        int target = 21;
        std::vector<int> result = subarraySum(nums, target);
    
        if (!result.empty()) {
            std::cout << "Subarray found from index " << result[0] << " to " << result[1] << std::endl;
        } else {
            std::cout << "No subarray found" << std::endl;
        }
    
        return 0;
    }
    

    Complexity Analysis

    The time complexity of this approach is O(n) because we traverse the array once. The space complexity is also O(n) due to the hash map storing cumulative sums.

    Edge Cases

    1. The array contains only one element equal to the target.

    2. The array contains negative numbers.

    3. The target is zero.

    4. No subarray sums to the target.

    Testing

    To test the solution comprehensively, consider the following test cases:

    • Simple cases with small arrays.
    • Arrays with negative numbers.
    • Large arrays to test performance.

    Thinking and Problem-Solving Tips

    When approaching such problems, consider using hash maps to store intermediate results for quick lookups. Practice similar problems to improve your problem-solving skills.

    Conclusion

    Understanding and solving this problem helps in developing efficient algorithms for finding subarrays with specific properties. Practice and explore further to enhance your skills.

    Additional Resources

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free