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 470
误落风尘
误落风尘 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:22

    O(NlogN) with simple data structures is sufficient.

    For contiguous subsequences, I think it means for subarrays.

    We maintain a prefix sum list, prefix[i] = sum for the first i elements. How to check if there exists a range rum between [low, high]? We can use binary search. So,

    prefix[0] = array[0]  
    for i in range(1, N) 
      prefix[i] = array[i] + prefix[i-1];
      idx1 = binarySearch(prefix, prefix[i] - low);
      if (idx1 < 0) idx1 = -1 - idx1;
      idx2 = binarySearch(prefix, prefix[i] - high);
      if (idx2 < 0) idx2 = -1 - idx2;
      // for any k between [idx1, idx2], range [k, i] is within range [low, high]
      insert(prefix, prefix[i])
    

    The only thing we need to care is we also need to insert new values, thus any array or linked list is NOT okay. We can use a TreeSet, or implement your own AVL trees, both binary search and insertion would be in O(logN).

提交回复
热议问题