Bitpath

Lesson 1 · Unit 01

From both ends

Find a pair with a given sum in a sorted list

11 exercisesabout 3 min

What you practise

  • Pair sum in a sorted array and why discarding is safe

Try a question from this lesson

Pick one

The sorted list is [1, 2, 4, 7, 11] and you need two numbers that sum to 9. You try smallest + largest: 1 + 11 = 12, too big. Which number can never be in an answer?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Two indexes, moving inward

On a sorted list, start lo at the smallest number and hi at the largest.

Sum too big? The largest is useless: move hi down. Too small? The smallest is useless: move lo up. Every step discards one number for good, so n numbers need at most n steps.

def pair_sum(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return [lo, hi]
        if s < target:
            lo += 1
        else:
            hi -= 1
    return []
function pairSum(nums, target) {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const s = nums[lo] + nums[hi];
    if (s === target) return [lo, hi];
    if (s < target) lo += 1;
    else hi -= 1;
  }
  return [];
}
function pairSum(
  nums: number[],
  target: number,
): number[] {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const s = nums[lo] + nums[hi];
    if (s === target) return [lo, hi];
    if (s < target) lo += 1;
    else hi -= 1;
  }
  return [];
}

Python notelo, hi = 0, len(nums) - 1 assigns both names in one statement: the right side is built as a tuple, then unpacked.

TypeScript noteThe return type number[] is honest but loose. [number, number] | [] would tell callers exactly what comes back: a pair of indexes or nothing.

9 more exercises in the app

  • 1× type the answer
  • 3× multiple choice
  • 2× fill the blanks
  • 1× true or false
  • 1× order the lines
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy