Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

The smallest difference between two arrays

Medium · Target 15 minutes · Two pointers· Type asked at

You're given two non-empty integer arrays a and b. Pick one value from each so that the absolute difference between them is as small as it can be, and return that difference.

Examples

InputOutputWhy
a = [1, 3, 15, 11, 2], b = [23, 127, 235, 19, 8]3I'd say 11 and 8 are the pair you want, because no other two values get within 3 of each other.
a = [10, 5, 40], b = [50, 90, 80]10You can't get any closer than 40 and 50, since everything else in b is up at 80 or 90.
a = [1, 2, 3], b = [3, 4]0There's a 3 in both of them, and you can't really do better than a gap of 0.

Constraints

  • 1 ≤ |a|, |b| ≤ 10⁵
  • −10⁶ ≤ a[i], b[j] ≤ 10⁶

Hints

Hint 1

If you try every pair it's O(|a| × |b|), so what do you think sorting both arrays would let you say about which pairs are even worth looking at?

Hint 2

Once they're both sorted you can put i at the start of a and j at the start of b, and if a[i] < b[j] I'd ask whether there's any point pairing a[i] with something later on in b.

Hint 3

There isn't, because everything later in b is even further away from a[i], so a[i] has had its best chance and i moves on (and it's the same thing for b[j] the other way round).

Where people lose marks

  • Moving the pointer on the bigger value. The gap can only grow that way, and you'll walk straight past the best pair.
  • Moving a pointer before you've updated the minimum, so that the last pair you look at before one array runs out never gets counted.
  • Computing a[i] − b[j] in 32 bits when the values can be near ±2 × 10⁹. Here they're capped at 10⁶ so it's safe, but I'd still say it.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.