#1679

Max Number of K-Sum Pairs

Medium
ArrayHash TableTwo PointersSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a hash map to count occurrences of each number. This allows us to efficiently find pairs that sum to k without needing nested loops.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hash map to count occurrences of each number in the array.
  2. 2Step 2: Iterate through each number in the array and calculate its complement (k - number).
  3. 3Step 3: Check if the complement exists in the hash map. If it does, calculate the number of pairs that can be formed and update the count.
  4. 4Step 4: Decrease the count of the current number and its complement in the hash map to avoid reusing them.
solution.py17 lines
1# Full working Python code
2
3def maxOperations(nums, k):
4    count = 0
5    freq = {}
6    for num in nums:
7        freq[num] = freq.get(num, 0) + 1
8    for num in nums:
9        complement = k - num
10        if complement in freq:
11            pairs = min(freq[num], freq[complement])
12            if num == complement:
13                pairs //= 2
14            count += pairs
15            freq[num] -= pairs
16            freq[complement] -= pairs
17    return count

Complexity note: The time complexity is O(n) because we make a single pass to count frequencies and another pass to find pairs. The space complexity is O(n) due to the hash map storing counts of each number.

  • 1Using a hash map can significantly reduce the time complexity.
  • 2Pairs can be formed by checking complements of each number.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.