THINK FIRST·CODE LATER

← All labs

Pairs with a given sum: Θ(n²) versus Θ(n)

Problem

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.

  1. Brute force: two nested loops over all pairs i < j. Count one comparison for every pair examined.
  2. 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 element x, add the number of times target - x has been seen, then record x. 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.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.