Start learning free

LESSON 235 OF 410 · PARTIAL SUMS #2

Subarray of Given Sum II in Python 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

    PYTHON · PARTIAL SUMS #2

    Subarray Of Given Sum in Python, explained

    Understanding the Problem

    The core challenge of this problem is to find a continuous subarray within an array of integers that sums up to a given 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

    We can optimize the solution using a hash map to store the cumulative sums and their corresponding indices. By iterating through the array and maintaining a running sum, we can check if the difference between the current sum and the target has been seen before. If it has, we have found our subarray.

    Algorithm

    1. Initialize a hash map to store cumulative sums and their indices.

    2. Initialize a variable to keep track of the cumulative sum.

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

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

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

    Code Implementation

    def subarray_sum(nums, target):
        # Dictionary to store the cumulative sum and its index
        sum_map = {}
        # Initialize the cumulative sum
        current_sum = 0
        
        # Iterate through the array
        for i, num in enumerate(nums):
            # Update the cumulative sum
            current_sum += num
            
            # Check if the current sum is equal to the target
            if current_sum == target:
                return [0, i]
            
            # Check if (current_sum - target) exists in the map
            if (current_sum - target) in sum_map:
                return [sum_map[current_sum - target] + 1, i]
            
            # Store the current sum and its index in the map
            sum_map[current_sum] = i
        
        # If no subarray is found, return an empty list
        return []
    
    # Example usage
    nums = [1, 1, 5, 2, 1, 3, 10, 2, 1]
    target = 21
    print(subarray_sum(nums, target))  # Output: [2, 6]
    

    Complexity Analysis

    The time complexity of this approach is O(n) because we iterate through the array once. The space complexity is also O(n) due to the hash map storing the 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:

    # Test case 1: Simple case
    assert subarray_sum([1, 2, 3, 4, 5], 9) == [1, 3]
    
    # Test case 2: Negative numbers
    assert subarray_sum([-1, -2, 3, 4, -5], 2) == [1, 3]
    
    # Test case 3: Single element equal to target
    assert subarray_sum([5], 5) == [0, 0]
    
    # Test case 4: No subarray sums to target
    assert subarray_sum([1, 2, 3], 7) == []
    

    Thinking and Problem-Solving Tips

    1. Break down the problem into smaller parts and understand the requirements.

    2. Consider edge cases and how your solution handles them.

    3. Practice similar problems to improve your problem-solving skills.

    Conclusion

    Understanding and solving the subarray sum problem is crucial for various applications. By using an optimized approach with a hash map, we can achieve an efficient solution with O(n) time complexity.

    Additional Resources

    1. LeetCode: Subarray Sum Equals K

    2. GeeksforGeeks: Find subarray with given sum

    3. Coding Ninjas: Subarray with Given Sum

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