Drill

ProblemsC# › patterns

The two readings that add up

mediumpatternsTwo pointersArraysC#

A reconciliation tool has a sorted column of amounts and a difference to explain. It looks for the two amounts that together account for it.

PairSummingTo(amounts: 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> amounts, int target) {
    
}

Worked examples

CallResult
PairSummingTo(new List<int> { 1, 2, 4, 7, 11 }, 9)new List<int> { 2, 7 }
PairSummingTo(new List<int> { 1, 2, 3, 4 }, 5)new List<int> { 1, 4 }
PairSummingTo(new List<int> { 1, 2, 3 }, 100)new List<int> { }
PairSummingTo(new List<int> { }, 3)new List<int> { }

Hint

Sorted input means you can start at both ends. If the two ends add up to too much, the right end is too big; if too little, the left end is too small.

Reference solution in C#
public List<int> PairSummingTo(List<int> amounts, int target) {
    int i = 0, j = amounts.Count - 1;
    while (i < j) {
        int sum = amounts[i] + amounts[j];
        if (sum == target) return new List<int> { amounts[i], amounts[j] };
        if (sum < target) i++;
        else j--;
    }
    return new List<int>();
}

The same problem in another language

More patterns problems in C#