Problem 1679

Abstract / Summary

Given an array of integers and a target sum k, find the maximum number of pairs whose elements add up to k.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1679.py

class Solution:
    def maxOperations(self, nums: List[int], k: int) -> int:
        result = 0

        freq = defaultdict(int)
        for n in nums:
            if freq[k - n] > 0:
                freq[k - n] -= 1
                result      += 1
            else:
                freq[n] += 1

        return result
13 lines | 333 bytes | submitted September 11, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The Solution.maxOperations method computes the maximum number of disjoint pairs that can be formed from the input list nums such that each pair sums to the target value k. It iterates through the list once, maintaining a frequency map of numbers that have not yet been paired. When a complementary value is found in the map, a pair is recorded and the complementary count is decremented; otherwise the current number is added to the map for potential future pairing. The final count of successful pairings is returned.

Key Steps

The algorithm begins by initializing a counter result to zero. This variable accumulates the total number of valid pairs discovered during the scan.

result = 0

A defaultdict of integers, named freq, is created to store the frequencies of numbers that are waiting for a complement. The use of defaultdict eliminates the need for explicit existence checks before updating counts.

freq = defaultdict(int)

The core of the method is a single for loop that processes each element n in nums. For each element, the algorithm checks whether the complement k - n already exists in the frequency map with a positive count. If such a complement is present, it indicates that a previously seen number can be paired with the current one. The complement’s count is decreased, and the result counter is incremented.

for n in nums:
    if freq[k - n] > 0:
        freq[k - n] -= 1
        result      += 1

If the complement is not available, the current number is stored in the frequency map, incrementing its count. This prepares the number to serve as a complement for a future element.

    else:
        freq[n] += 1

After the loop finishes, the method returns the accumulated number of pairs.

return result

Edge Cases Handled

When the input list contains duplicate values, the frequency map correctly tracks how many instances of each value are still unpaired. For example, if nums includes multiple occurrences of a number that is exactly half of k, the algorithm will only pair them when two such numbers appear consecutively or when a later element provides the needed complement. The condition freq[k - n] > 0 ensures that a pair is formed only when a complementary entry exists, preventing premature consumption of values.

If k is an even number and the list contains many elements equal to k/2, the algorithm treats each occurrence as a potential partner for another identical element. The decrement of the complement count and the increment of result happen atomically, guaranteeing that each element participates in at most one pair.

When nums is empty, the loop body never executes, leaving result at its initial value of zero, which is correctly returned. Similarly, if no two numbers sum to k, the frequency map will simply accumulate all elements, and result will remain zero throughout, reflecting the absence of valid operations.

Performance Optimizations

The implementation leverages a hash-based frequency map (defaultdict) to achieve constant-time lookups and updates for complements. By checking for the existence of a needed partner before inserting the current number, the algorithm avoids unnecessary storage of numbers that can be immediately paired, reducing the size of the map.

The single pass over nums ensures that each element is examined exactly once, eliminating redundant scans. The in-place decrement of the complement count (freq[k - n] -= 1) reuses the existing entry rather than creating a new one, which minimizes memory churn.

Using defaultdict(int) automatically initializes missing keys to zero, allowing the condition freq[k - n] > 0 to be evaluated without additional guard clauses. This streamlines the control flow and reduces branching overhead.

Overall, the combination of a single traversal, constant-time hash operations, and immediate pairing when possible yields an efficient solution that scales well with the size of the input list.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of numbered blocks. Your goal is to find pairs of blocks that add up to the number k. To do this, you carry a little box around with you. You pick up one block at a time from the pile and look at it. Before you decide what to do with that block, you check your box to see if you already put a matching block in there that could help you make a pair.

If you find a match in your box, you take that matching block out and put it together with the block in your hand to finish a new pair. Once you have a pair, you set it aside nicely. If you do not find a matching block waiting for you in your box, you simply place the block from your hand into the box for someone else to find later. You keep doing this until there are no blocks left in the pile, always watching for those perfect pairs that add up to k.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.96 | σ = 1.07

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
30 links | 18 authors | 9 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

11 solutions   September 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality