KatInterview

Cross-Array Pair Sum Check on Two Ordered Lists

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingtwo-pointerssorted-arraystwo-sum

Last updated

Decide whether one value from each of two sorted lists adds up to a target, using a linear-time opposite-direction two-pointer scan with constant extra space.

You are given two lists of integers, first and second, each sorted in non-decreasing order, and an integer goal.

Determine whether it is possible to choose exactly one value from first and exactly one value from second so that the two chosen values add up to goal.

Both values must come from different lists: two elements taken from the same list never count as a valid pair. Duplicate values are allowed in either list, and a value may be used as long as it appears in its own list.

Task

Implement pair_sum_across_lists(first, second, goal), which returns True if such a pair exists and False otherwise.

If either list is empty, no pair can be formed, so the answer is False.

Aim for a solution that runs in time proportional to len(first) + len(second) and uses only constant extra memory. Your comparison logic should also be conceptually safe for 64-bit signed integer ranges, meaning it should not rely on intermediate values that would fall outside that range in a fixed-width language. (Python integers do not overflow, so a direct sum is fine in Python.)

Input

  • first: a list of integers sorted in non-decreasing order.
  • second: a list of integers sorted in non-decreasing order.
  • goal: an integer.

Output

  • A boolean: True if some a in first and some b in second satisfy a + b == goal, otherwise False.

Constraints

  • 0 <= len(first), len(second) <= 10^6
  • -2^63 <= first[i], second[j], goal <= 2^63 - 1
  • Both lists are sorted in non-decreasing order.
  • Target complexity: O(len(first) + len(second)) time and O(1) extra space.

Examples

Example 1

Input: pair_sum_across_lists([1, 3, 5, 8], [2, 4, 9, 11], 14)

Output: True

Example 2

Input: pair_sum_across_lists([-10, -3, 0, 4], [-5, 1, 7], -15)

Output: True

Example 3

Input: pair_sum_across_lists([1, 2, 3], [4, 5, 6], 20)

Output: False

Hints

Hint 1

Think about the classic two-sum on a single sorted array, where one pointer starts at each end. Here the two ends belong to different lists.

Hint 2

Start at the smallest element of the first list and the largest element of the second list. If their sum is too small, which pointer can move to raise it? If too large, which can lower it?

Hint 3

Each step permanently discards one element that cannot be part of any valid pair, so the scan ends after at most len(first) + len(second) steps. Empty lists make the loop never execute.