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 485
误落风尘
误落风尘 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:05

    If all integers are non-negative, then it can be done in O(max(size-of-input,size-of-output)) time. This is optimal.

    Here's the algorithm in C.

    void interview_question (int* a, int N, int lo, int hi)
    {
      int sum_bottom_low = 0, sum_bottom_high = 0,
          bottom_low = 0, bottom_high = 0,
          top = 0;
      int i;
    
      if (lo == 0) printf ("[0 0) ");
      while (top < N)
      {
        sum_bottom_low += a[top];
        sum_bottom_high += a[top];
        top++;
        while (sum_bottom_high >= lo && bottom_high <= top)
        {
          sum_bottom_high -= a[bottom_high++];
        }
        while (sum_bottom_low > hi && bottom_low <= bottom_high)
        {
          sum_bottom_low -= a[bottom_low++];
        }
        // print output
        for (i = bottom_low; i < bottom_high; ++i)
          printf ("[%d %d) ", i, top);
      }
      printf("\n");
    }
    

    Except for the last loop marked "print output", each operation is executed O(N) times; the last loop is executed once for each interval printed. If we only need to count the intervals and not print them, the entire algorithm becomes O(N).

    If negative numbers are allowed, then O(N^2) is hard to beat (might be impossible).

提交回复
热议问题