KatInterview

Count Maximum Disjoint Pairs Summing to a Target

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashinghash-mapcountingtwo-pointers

Last updated

Find the most index-disjoint pairs in an integer array whose values add up to a target, testing hashing of complements, counting, and handling of the self-pairing case.

Count Maximum Disjoint Pairs Summing to a Target

You are given a list of integers values and an integer target.

A move picks two different positions i and j in the list such that values[i] + values[j] == target, and then takes both of those positions out of play. A position that has been taken out cannot be used in any later move, so every position belongs to at most one move.

Return the largest possible number of moves that can be made.

Details

  • Only the values matter, not where they sit in the list. Any two distinct positions may be paired, regardless of which one comes first.
  • A single position can never be paired with itself. For example, if target is 6 and the list holds just one 3, that 3 has no partner.
  • If target is even, copies of target / 2 can be paired with one another, but each copy still serves in at most one pair.
  • Values may be negative or zero.
  • If no valid pair exists (including when the list is empty or has one element), return 0.

Constraints

  • 0 <= len(values) <= 10^5
  • -10^9 <= values[i] <= 10^9
  • -2 * 10^9 <= target <= 2 * 10^9
  • The input list may be modified or left untouched; only the returned integer is checked.

Examples

Example 1

Input: max_pairs_with_sum([1, 2, 3, 4], 5)

Output: 2

Example 2

Input: max_pairs_with_sum([3, 1, 3, 4, 3], 6)

Output: 1

Hints

Hint 1

Does the order of the elements matter, or only how many copies of each value exist?

Hint 2

A value v can only be matched with the value target - v. Think about how many pairs a group of v's and a group of target - v's can produce, and treat the case v == target - v separately.

Hint 3

Scan once while keeping a table of unmatched values. For each element, first check whether its complement is waiting in the table; only if not, add the element itself to the table.