KatInterview

Enumerate All Index Pairs Adding Up to a Goal Value

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashinghash-maptwo-sumduplicates

Last updated

Tests hash-map indexing of duplicate values to list every index pair i < j whose values sum to a goal, in a specific sorted output order.

Enumerate All Index Pairs Adding Up to a Goal Value

You are given a list of integers values and an integer goal. Return every pair of positions [i, j] in the list such that i < j and values[i] + values[j] == goal.

The list may contain repeated numbers, and each position counts separately. Every qualifying combination of positions must be reported, not just one match per value. For instance, with values = [1, 1, 1] and goal = 2, the pairs [0, 1], [0, 2] and [1, 2] all qualify.

Output format

  • Return a list of two-element lists [i, j], each with i < j.
  • Each pair appears exactly once.
  • Order the pairs by i ascending, and for equal i by j ascending.
  • An element cannot be paired with itself (the same position cannot be used twice).
  • If no pair qualifies, or the list has fewer than two elements, return an empty list.

Constraints

  • 1 <= len(values) <= 10^4
  • -10^6 <= values[i] <= 10^6
  • -2 * 10^6 <= goal <= 2 * 10^6

Examples

Example 1

Input: find_index_pairs_with_sum([2, 7, 11, 15], 9)

Output: [[0, 1]]

Example 2

Input: find_index_pairs_with_sum([1, 2, 1, 2], 3)

Output: [[0, 1], [0, 3], [1, 2], [2, 3]]

Example 3

Input: find_index_pairs_with_sum([1, 1, 1], 2)

Output: [[0, 1], [0, 2], [1, 2]]

Hints

Hint 1

Plain Two Sum stops at the first match. Here a value can combine with every position that holds its complement, so think about storing all positions per value.

Hint 2

Build a dictionary from each value to the ascending list of positions where it occurs. Then for each i, look up goal - values[i] and consider only positions j greater than i.

Hint 3

If you iterate i upward and each stored position list is ascending, the output is automatically in the required (i, j) order. Be careful that when a value is half the goal, position i appears in its own complement list and must be skipped.