714141. Yet another query problem
Medium
Yet Another Query Problem
Summary
Given an array of integers, your task is to find all pairs that sum up to a given target value. This problem involves using prefix sums and arrays, making it a medium-level difficulty query problem.
Detailed Explanation
The basic idea is to use the property of prefix sums: if we have two indices i and j, such that arr[i] + arr[j] = target, then their prefix sums should be equal. We iterate over the array once, calculate the prefix sum for each element, and store it in a hash map.
Here's a step-by-step breakdown of the solution:
- Initialize an empty hash map
prefixSumMap. - Iterate over the array from left to right:
- Calculate the prefix sum
psfor each element. - Check if there exists another element
jsuch thatarr[j] + ps = target. If found, return the pair(arr[i], arr[j]).
- Calculate the prefix sum
- Return an empty list if no pairs are found.
Time complexity: O(n), where n is the length of the array. We only iterate over the array once. Space complexity: O(n), for storing the prefix sums in the hash map.
Here's a simple ASCII art diagram to illustrate the process:
arr = [1, 2, 3, 4]
ps_map = {}
i = 0
while i < len(arr):
ps = sum(arr[:i+1]) # prefix sum up to i
if target - ps in ps_map:
return [(arr[i], x) for x in ps_map[target-ps]]
ps_map[ps] = arr[i]
i += 1
Optimized Solutions
Java
public List<int[]> findPairs(int[] arr, int target) {
Map<Integer, Integer> prefixSumMap = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int ps = 0;
for (int j = 0; j <= i; j++) {
ps += arr[j];
}
if (prefixSumMap.containsKey(target - ps)) {
return Arrays.stream(prefixSumMap.get(target - ps)).boxed().collect(Collectors.toList());
}
prefixSumMap.put(ps, arr[i]);
}
return new ArrayList<>();
}