I face a problem, where I need to find a specific pairwise sum where the first element from the index has index > i.
Example:
[1, 2, 3, 4, 6] (index 0 to 4)
target_sum = 9
Now, from this array I need to find a pairwise sum where the first element from the index has index > i.
Now, the obvious solution is:
- Calculate the pairwise sum array.
[1+2, 1+3, 1+4, 1+6, 2+3, 2+4, 2+6, 3+4, 3+6, 4+6][ O(n^2) ] - Loop through index
i+1tonto find the target_sum. [ O(n^2) ] (n being the length of original array)
Now, the main issue is 2. Even if I can't improve (1), I need to improve (2), as this will be queried a lot.
One approach that comes to my mind:
- Make an array of index, value pair from the pairwise sum array. O(n^2) [n being the original length]
- Sort the array first with value, then with index. O(n^2 * logn)
- For each query, run a binary search to find the interval where the value exists. O(logn)
- Run another binary search on that interval to find the index >
i.
Is there any elegant and better approach?
Create a map
sum -> highest first element indexinO(n^2). Then answer each query inO(1)by looking up the target sum in the map and deciding ifhighest first element indexis higher thani.