Subarray Sum – Python 3 (Week 13 – 10)

class Solution:
    """
    @param nums: A list of integers
    @return: A list of integers includes the index of the first number and the index of the last number
    """
    def subarraySum(self, nums):
        # write your code here
        
        if not nums:
            return []
        prefixsum = {0: -1}
        nowsum = 0
        
        for i in range(len(nums)):
            nowsum += nums[i]
            if nowsum in prefixsum:
                return [prefixsum[nowsum] + 1, i]
            prefixsum[nowsum] = i

            
        return[]
        

Time O(n). Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started