1

Subarray problem: Given integer array A (only positive numbers), is there a continuous subarray of any length with sum S? Sliding window solution to this is O(N).

Now if we have many such queries S on static array, we can do preprocessing. We can compute all subarray sums in O(N^2) and store them in a hash table. This also takes up O(N^2) space. Then we can process the queries in O(1) just looking up S from the hashtable

My question is, is there some O(N log N) prepeprocessing? Even if that means droping the queries to O(log N).

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Filip Nguyen
  • 1,029
  • 1
  • 7
  • 20
  • What is `Sliding window solution to this is O(N)` approach ? Have you fully specified the problem? – MBo Sep 24 '17 at 05:34
  • Do you fully understand the basic subarray sum problem that is well known? – Filip Nguyen Sep 24 '17 at 05:41
  • That seems a bit difficult as to choose a sub array you will have to choose two indices ant that amounts to O(N**2) – Vinayak Singla Sep 24 '17 at 05:56
  • @VinayakSingla intuitivelly it seems that it should be possible by clever augmentation of a segment tree no? – Filip Nguyen Sep 24 '17 at 06:02
  • @Filip Nguyen There are some kinds of "subarray sum problem". Are all numbers positive? Is subarray length predefined? Does mentioned solution use O(1) of additional memory? – MBo Sep 24 '17 at 08:37
  • @Mbo I modified the question to include more information. All numberes are positive, the subarray length is not predefined it can be arbitrary. The known solution has O(1) - http://www.geeksforgeeks.org/find-subarray-with-given-sum/ – Filip Nguyen Sep 24 '17 at 08:41

1 Answers1

0

is there some O(N log N) prepeprocessing?

No.

There are N2 possible subarrays in an array of size N. You cannot generate output of size N2 in less than O(N2) time.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • I dont require to generate N^2 hashtable using N log N preprocessing. The goal is that after *some* the preprocessing is done, it will be possible to query with at worst O(log N) time – Filip Nguyen Sep 24 '17 at 09:10