Given an array of n integers and a target, count the pairs of positions i < j with a[i] + a[j] == target. Solve the problem twice and count the work each method does — do not measure time.
- Brute force: two nested loops over all pairs i < j. Count one comparison for every pair examined.
- Hash map: scan the array once, keeping a
Map<Long, Long>from each value seen so far to how often it has been seen. For each elementx, add the number of timestarget - xhas been seen, then recordx. Count one lookup per element.
Input: n, then n integers, then target (values fit in an int, but sums may not — use long). Output exactly:
Brute force: <pairs> pairs, <comparisons> comparisons
Hash map: <pairs> pairs, <lookups> lookups
For the input
5
1 5 7 -1 5
6
the output is
Brute force: 3 pairs, 10 comparisons
Hash map: 3 pairs, 5 lookups
(the pairs are 1 + 5, 1 + 5 and 7 + (−1)). Both methods must always report the same number of pairs.