Drill

ProblemsC# › warmup

Find the two that add up

mediumwarmupHash mapsArraysC#

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

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

C# 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

public List<int> PairSummingTo(List<int> values, int target) {
    
}

Worked examples

CallResult
PairSummingTo(new List<int> { 2, 7, 11, 15 }, 9)new List<int> { 0, 1 }
PairSummingTo(new List<int> { 3, 2, 4 }, 6)new List<int> { 1, 2 }
PairSummingTo(new List<int> { 3, 3 }, 6)new List<int> { 0, 1 }
PairSummingTo(new List<int> { 1, 2 }, 99)new List<int> { }

Hint

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

Reference solution in C#
public List<int> PairSummingTo(List<int> values, int target) {
    var seen = new Dictionary<int, int>();
    for (int j = 0; j < values.Count; j++) {
        int v = values[j], need = target - v;
        if (seen.ContainsKey(need)) return new List<int> { seen[need], j };
        if (!seen.ContainsKey(v)) seen[v] = j;
    }
    return new List<int>();
}

The same problem in another language

More warmup problems in C#