Drill

ProblemsJava › warmup

Find the two that add up

mediumwarmupHash mapsArraysJava

A reconciliation tool looks for the two entries that together explain a difference.

pairSummingTo(values: list<int>, target: int) → list<int>

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

List<Integer> pairSummingTo(List<Integer> values, int target) {
    
}

Worked examples

CallResult
pairSummingTo(Main.<Integer>ls(2, 7, 11, 15), 9)Main.<Integer>ls(0, 1)
pairSummingTo(Main.<Integer>ls(3, 2, 4), 6)Main.<Integer>ls(1, 2)
pairSummingTo(Main.<Integer>ls(3, 3), 6)Main.<Integer>ls(0, 1)
pairSummingTo(Main.<Integer>ls(1, 2), 99)Main.<Integer>ls()

Hint

Walk once, and for each value ask whether the number that would complete it has already gone by.

Reference solution in Java
List<Integer> pairSummingTo(List<Integer> values, int target) {
    Map<Integer, Integer> seen = new HashMap<>();
    for (int j = 0; j < values.size(); j++) {
        int v = values.get(j), need = target - v;
        if (seen.containsKey(need)) return new ArrayList<>(Arrays.asList(seen.get(need), j));
        if (!seen.containsKey(v)) seen.put(v, j);
    }
    return new ArrayList<>();
}

The same problem in another language

More warmup problems in Java