Google Interview: Find all contiguous subsequence in a given array of integers, whose sum falls in the given range. Can we do better than O(n^2)?

前端 未结 7 481
误落风尘
误落风尘 2021-01-30 02:35

Given an array of Integers, and a range (low, high), find all contiguous subsequence in the array which have sum in the range.

Is there a solution b

7条回答
  •  情歌与酒
    2021-01-30 03:24

    Starting from this problem: find all contiguous sub-sequences that sum to x. What we need is something similar.

    For every index i, we can calculate the sum of the segment from 0 to i, which is x. So, the problem now is we need to find from 0 to i - 1, how many segments have sum from (x - low) to (x - high), and it should be faster than O(n). So there are several data structures help you to do that in O(logn), which are Fenwick tree and Interval tree.

    So what we need to do is:

    • Iterating through all index from 0 to n (n is the size of the array).

    • At index ith, calculate, starting from 0 to ith index, the sum x, query the tree to get the total occurrences of numbers fall in the range (x - high, x - low).

    • Add x to the tree.

    So the time complexity will be O(n log n)

提交回复
热议问题