Subsequence sum

后端 未结 5 1188
天命终不由人
天命终不由人 2021-01-30 18:23

Given an array of integers eg [1, 2, -3, 1] find whether there is a sub-sequence that sums to 0 and return it (eg [1, 2, -3] or [2,

5条回答
  •  隐瞒了意图╮
    2021-01-30 19:02

    Do a running sum, storing sum values in a hash table along with array index

    If you ever get a sum value you’ve already seen, return 1+the index in the hash table, and the current index. This solution is O(n) time complexity.

    No need for a new array. Space complexity is O(N) because of the hash.


    A Python implementation:

    input = [1, 4, -3, -4, 6, -7, 8, -5]
    map = {}
    sum = 0
    for i in range(len(input)):
        sum += input[i]
        if sum in map:
            print map[sum][0] + 1, "to", i
        map[sum] = (i, sum)
    

    Notice that repeated subsequences are not shown, example: If (1 to 2) is a subsequence and (3 to 4), (1 to 4) won't be shown. You can achieve this behavior by storing lists in each position of the map:

    for x in map[sum]:
        print x[0]+1, "to", i
    map[sum].append((i, sum))
    

提交回复
热议问题