Max Number of K-Sum Pairs

Medium Hash Maps

Problem

Given an integer array nums and an integer k, return the maximum number of operations where each operation consists of removing two elements from nums whose sum equals k.

  • 1 ≤ nums.length ≤ 10⁵
  • 1 ≤ nums[i], k ≤ 10⁹

Example

Input: nums = [1,2,3,4], k = 5
Output: 2

The brute-force approach would check all pairs to find sums equal to k, which is O(n^2) and inefficient for large inputs. Instead, the algorithm uses a hash map to track counts of numbers seen so far. For each number, it checks if its complement (k - num) exists in the map with a positive count. If so, it forms a valid pair, increments the operation count, and decrements the complement's count. Otherwise, it increments the count of the current number. This approach efficiently finds pairs in a single pass.

Approach

Straightforward Solution

A brute-force solution would check every pair of elements to see if they sum to k, resulting in O(n^2) time complexity, which is too slow for large inputs.

Core Observation

The problem reduces to finding pairs of numbers that sum to k, where each number can only be used once. This naturally suggests tracking frequencies of numbers and their complements.

Path to Optimal

Recognizing that for each number num, the complement needed is k - num, the problem can be transformed into a frequency lookup problem. Using a hash map to store counts of numbers seen so far allows checking for complements in O(1) average time. This reduces the problem to a single pass through the array, updating counts and counting valid pairs.

Optimal Approach

Iterate through nums once. For each num, check if the complement k - num exists in the hash map with a positive count. If yes, decrement the complement count and increment the operations count. Otherwise, increment the count of num in the map. Return the total operations count after processing all elements.

Time

O(n)

The algorithm iterates through the nums array once, performing O(1) average-time hash map operations for each element.

Space

O(n)

In the worst case, all elements are stored in the hash map if no pairs are found, requiring O(n) auxiliary space.

Pattern Spotlight

Hash Maps (Frequency Counting for Complement Lookup)

When pairing elements based on a sum or difference condition, use a hash map to track frequencies of seen elements and check for complements in constant time to achieve a linear-time solution.

Solution

1class Solution:
2 def maxOperations(self, nums: list[int], k: int) -> int:
3 count = {}
4 operations = 0
5
6 for num in nums:
7 complement = k - num
8
9 if count.get(complement, 0) > 0:
10 count[complement] -= 1
11 operations += 1
12 else:
13 count[num] = count.get(num, 0) + 1
14
15 return operations

Step-by-Step Solution

1

Initialize Frequency Map and Operation Counter

3count = {}
4operations = 0

Objective

To prepare data structures for tracking counts of numbers and the number of valid pairs found.

Key Insight

A hash map is used to store the frequency of numbers that have not yet been paired. The operations counter tracks how many valid pairs have been formed. This setup enables efficient complement checks during iteration.

Interview Quick-Check

Core Logic

The hash map stores counts of unpaired numbers, enabling O(1) average-time complement lookups.

State & Boundaries

The operations counter starts at zero and increments only when a valid pair is found.

2

Iterate Through Array and Count Valid K-Sum Pairs

6for num in nums:
7 complement = k - num
9 if count.get(complement, 0) > 0:
10 count[complement] -= 1
11 operations += 1
13 count[num] = count.get(num, 0) + 1

Objective

To process each number, check for its complement, and update counts and operations accordingly.

Key Insight

For each number, the algorithm checks if its complement exists with a positive count. If so, it forms a pair by decrementing the complement's count and incrementing the operations count. Otherwise, it increments the count of the current number. This approach ensures each element is used at most once and all pairs are counted efficiently in a single pass.

Interview Quick-Check

Core Logic

Check for complement before adding the current number to avoid double counting and ensure each element is used once.

Common Pitfalls & Bugs

Failing to decrement the complement's count after pairing leads to counting the same element multiple times.

Complexity

Single pass iteration with O(1) average hash map operations yields O(n) time complexity.

3

Return Total Number of Valid Operations

15return operations

Objective

To output the total count of valid pairs found after processing the entire array.

Key Insight

Returning the operations counter after the loop completes provides the maximum number of k-sum pairs that can be formed without reusing elements.

Interview Quick-Check

Core Logic

Returning the operations count reflects the total number of valid pairs formed.

Line Analysis

This solution has 2 Critical lines interviewers watch for.

Line 9 Critical
if count.get(complement, 0) > 0:

Check if the complement exists with a positive count in the frequency map.

This condition identifies whether a valid pair can be formed with the current number and a previously seen complement.

Line 10 Critical
count[complement] -= 1

Decrement the count of the complement as it is now paired.

Reducing the complement's count prevents reuse of the same element in multiple pairs, ensuring correctness.

Line 3 Core
count = {}

Initialize a hash map to store counts of unpaired numbers.

This data structure enables constant-time lookups for complements, which is essential for achieving linear time complexity.

Line 11 Core
operations += 1

Increment the operations counter to reflect a successful pair.

Counting the pair here ensures the final result accurately reflects the number of valid operations performed.

Line 7 Core
complement = k - num

Calculate the complement needed to form a pair summing to k.

The complement is the key value to check in the frequency map to determine if a valid pair exists.

Line 13 Core
count[num] = count.get(num, 0) + 1

Increment the count of the current number in the frequency map if no complement was found.

Storing the current number's count allows it to be matched with future complements, enabling pairing in subsequent iterations.

Line 15 Standard
return operations

Return the total number of valid pairs found.

This final return statement outputs the maximum number of operations possible, completing the algorithm.

Line 4 Standard
operations = 0

Initialize a counter for the number of valid operations (pairs).

This variable accumulates the total count of pairs found, which is the final result.

Line 6 Standard
for num in nums:

Begin iterating through each number in the input array.

Processing each element sequentially allows the algorithm to build and check the frequency map dynamically.

Test Your Understanding

Why do we check for the complement's existence before adding the current number to the hash map?

Checking for the complement first ensures that each pair is counted exactly once and prevents using the same element twice in a pair.

Related Problems

Hash Maps pattern

Don't just read it. Drill it.

Reconstruct Max Number of K-Sum Pairs from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Max Number of K-Sum Pairs drill

or drill a free problem