Bitpath

Lesson 1 · Unit 03

Merge two sorted lists

Two pointers, one pass, and do not forget the leftovers

12 exercisesabout 3 min

What you practise

  • Two pointers, the leftover tail, O(n + m)

Try a question from this lesson

Pick one

Two piles of exam papers are each sorted by score, lowest on top. You want one sorted pile. Where is the lowest paper of all?

The idea

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

Concept

Merge

Keep one pointer per list: i in a, j in b. Compare the two items they point at, copy the smaller one to the output, and advance that pointer.

The loop ends when either list runs out. Whatever is left in the other list is already sorted and larger than everything copied so far, so it is appended as it is.

def merge(a, b):
    out = []
    i = j = 0
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            out.append(a[i])
            i += 1
        else:
            out.append(b[j])
            j += 1
    return out + a[i:] + b[j:]
function merge(a, b) {
  const out = [];
  let i = 0, j = 0;
  while (i < a.length && j < b.length) {
    if (a[i] <= b[j]) {
      out.push(a[i]);
      i++;
    } else {
      out.push(b[j]);
      j++;
    }
  }
  out.push(...a.slice(i), ...b.slice(j));
  return out;
}
function merge(a: number[], b: number[]) {
  const out: number[] = [];
  let i = 0, j = 0;
  while (i < a.length && j < b.length) {
    if (a[i] <= b[j]) {
      out.push(a[i]);
      i++;
    } else {
      out.push(b[j]);
      j++;
    }
  }
  out.push(...a.slice(i), ...b.slice(j));
  return out;
}

Python noteA slice that starts past the end, like a[i:] when i == len(a), is just an empty list. So one of the two tails adds nothing.

JavaScript noteout.push(...a.slice(i)) spreads the leftover items into separate arguments, so each one is pushed.

TypeScript noteconst out: number[] = [] needs its annotation: an empty array literal gives TypeScript nothing to infer the item type from.

10 more exercises in the app

  • 2× type the answer
  • 4× multiple choice
  • 1× fill the blanks
  • 2× true or false
  • 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