You get arrays, a list of at least two lists of whole numbers, and each inner list is sorted from smallest to largest.
Choose one number from one list and one number from a different list. Their distance is the absolute value of their difference. Return the largest distance you can get.
Example 1
Input: arrays = [[2, 6], [-1, 0, 3], [5, 9]] Output: 10 Why: take −1 from the second list and 9 from the third
2 more examples and the constraints
Example 2
Input: arrays = [[1, 10], [4, 5], [3, 6]] Output: 7 Why: 10 − 3; the pair 1 and 10 share a list, so 9 is not allowed
Example 3
Input: arrays = [[-3], [-3]] Output: 0 Why: the only choice is −3 and −3
Constraints
- 2 ≤ number of lists ≤ 100,000
- 1 ≤ length of each list ≤ 500, and at most 100,000 numbers in total
- −10,000 ≤ each number ≤ 10,000
- Every list is sorted in ascending order
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every pair of arraysO(m²)
- One pass, smallest and largest so farO(m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 lists | Verdict |
|---|---|---|---|
| Every pair of arrays | O(m²) | Correct; billions of pairs at the limit | |
| One pass, smallest and largest so far | O(m) | Best; one look at each list |
m = number of lists. Only the first and last number of each list are ever read.
Edge cases to test
- Extremes in one list. If the overall smallest and largest share a list, their gap is not allowed; Example 2 shows it.
- All values equal. Every distance is 0, so return 0.
- Single-number lists. First and last are the same number; the method still works.
- Only two lists. The loop runs once and compares both directions.
Common mistakes
- Returning global max minus global min, which may pick both numbers from the same list.
- Updating
loandhibefore checking the current list, so a list is paired with itself. - Reading every number instead of just the two ends of each sorted list.
How to talk through it
- 1Clarify. Must the two numbers come from different lists? Can a list have one number?
- 2Use the sorting. Only the first and last values of each list can be part of the best pair.
- 3Give the pair check. Compare every two lists both ways: correct, O(m²).
- 4Keep running extremes. Pair each list with the smallest first and largest last seen before it, then fold it in.
- 5Test out loud. Try extremes in one list, equal values and two single-number lists.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?