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.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d6-1-data-1.txt

5
1 5 7 -1 5
6
What your program must print for d6-1-data-1.txt
Brute force: 3 pairs, 10 comparisons
Hash map: 3 pairs, 5 lookups

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d6-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content d6-1-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

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.