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 484
误落风尘
误落风尘 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:21

    Here is way you can get O(nlogn) if there are only positive numbers :-

    1. Evaluate cumulative sum of array
    2. for i  find total sum[j] in (sum[i]+low,sum[i]+high) using binary search
    3. Total = Total + count
    4. do 3 to 5 for all i
    

    Time complexity:-

    Cumulative sum is O(N)
    Finding sums in range is O(logN) using binary search
    Total Time complexity is O(NlogN)
    

提交回复
热议问题